Delegates:

1.Delegate in C# language is used for storing functions. 2.Delegates used for creating call back functions. 3.Delegates are internally treated as classes.

Types of Delegates:

  1. Single cast delegate
  2. Multi cast delegate

Delegate syntax:

acces-specifier delegate return-type (data-type variable1,data-type variable 2,...);

Storing methods in delegates:

A delegate object can store method in its invocation or calling list, for more details see the following sample code.
namespace DelegateEx{
public delegate int D1(int x,int y);
public class A
{
  public int M(int x,int y) {return x+y;}
}
 public class Test
 {
   public static void Main(string[] args)
   {
     A a=new A();
     D1 d1=new D1(a.M);
     //Above code will create delegate object and will store address of object a as well as method name M.
     d1(10,20);//this code will call method M present in Class A.
   }
 }
}

Memory representation for the above Program:


a
b
0X200
0X300
0X200
0X300
public int M(int x,int y)
{
   return x+y;
}
delegate object stores address of A class object and Method name M.
0X200;M
Memory created for delegate object.

Code discussion:

In the above given sample code delegate object is storing A class object address as well as method M which belongs to it.
During execution of d1(10,20) CLR converts the same into 0X200.M(10,20) and calls the method M which is associated with A class object.
Note:we can store an instance method or a static method in the delegates invocation list.

Singlecast delegate:

A singlecast delegate contains only one method in its invocation or calling list. Ex: the above given sample code is a single cast delegate sample.

Multicast delegate:

A Multicast delegate is a delegate which contains more than one method in its invocation sequence.
Note:There is no special syntax for declaring a multicast delegate.

Multicast delegate sample:

 namespace MulticastDelegateEx{
 public delegate void D1(int x,int y);
 public class A
 {
    public void M1(int x,int y){ int r=x+y; }
 }
 public class B
 {
    public void M2(int x1,int y1){ int r1=x1+y1; }
 }
 public class Test
 {
   public static void Main(string[] args)
   {
     A a=new A();
     D1 d1=new D1(a.M1);//d1 is a singlecast delegate since it contains only one method.
     B b=new B();
     D1 d2=new D1(b.M2);//d2 is a singlecast delegate since it contains only one method.
     D1 d3=d1+d2;//d3 is a single cast delegate, it contains M1,M2 methods in its calling list.
     d3(10,20);//this code will call method M1,M2 methods in the sequence.
   }
 }
 }