You are on page 1of 12

Delegates

Contents

 What is Delegate ?
 Types of Delegate.
 Syntax.
 characteristics.
 Code Explanation.
 Conclusion.
What Is Delegate ?

 Delegates are type safe, object


oriented, secure .NET objects which
can be used to invoke methods of
matching signature.
Syntax

 delegate result-type identifier


([parameters]);
1. result-type : The result type, which matches
the return type of the function.
2. Identifier : The delegate name.
3. Parameters : The Parameters, that the
function takes.
Types of Delegate

 Single Cast Delegate

 Multi Cast Delegate


Three Steps in defining and using
delegates:
 Declaration

 Instantiation

 Invocation
Code for Single cast Delegate
 using System;
namespace BasicDelegate
{
      public delegate void SimpleDelegate(); // Declaration
    class TestDelegate  
    {
        public static void MyFunc()
        {
            Console.WriteLine("I was called by delegate ...");
        }
        public static void Main()
        {
           // Instantiation
            SimpleDelegate simpleDelegate = new SimpleDelegate(MyFunc);
                        simpleDelegate(); // Invocation
        }
    }
}
Code for Multi cast Delegate
 using System;
using System.Collections.Generic;
using System.Text;

namespace delegates
{
delegate void methodInvoker();

class Program
{
Program()
{
methodInvoker m = null;
m += new methodInvoker(Food);
m += new methodInvoker(Good);
m();
}
Condt:-
 void Food()
{
Console.WriteLine("Hi I am Food ");

}
void Good()
{
Console.WriteLine("Hi I am Good ");

static void Main(string[] args)


{
new Program();
Console.Read();
}
}
}
Characteristics
 It is class which can be
instantiated .
 Delegates Can be used
to define callback
methods.
 Delegates can be used to
chained together; for
example, multiple methods
can be called on a single
event.
Conclusion

 A delegate is just about the equivalent of


function pointers except that delegates are
objects and are type safe.
 Delegates can reference both static and
instance methods of a class.
 Delegates can be passed as arguments to
functions.
Thank You

You might also like