Please enable Javascript to correctly display the contents on Dot Net Tricks!

C Sharp Delegates and Plug-in Methods with Delegates

  Author : Shailendra Chauhan
Updated On : 19 Jul 2013
Total Views : 87,646   
 

Delegate is a reference type that holds the reference of a class method. Any method which has the same signature as delegate can be assigned to delegate. Delegate is like function pointer in C++. There are three aspects to a delegate: Declaration, Instantiation and Invocation.

Declaration:

A delegate is declared by using the keyword delegate, otherwise it resembles a method declaration.

 delegate int delegateAdd (int x,int y); 

Instantiation:

To create a delegate instance, we need to assign a method (which has same signature as delegate) to delegate.

 static int Add (int x,int y) 
{
 return x+y;
 }
..
//create delegate instance
delegateAdd objAdd= new delegateAdd (Add);
//short hand for above statement
delegateAdd objAdd=Add; 

Invocation:

Invoking a delegate is like as invoking a regular method.

 // Invoke delegate to call method
int result = objAdd.Invoke (3,6); 
//short hand for above statement
int result = objAdd (3,6); 

Plug-in Methods with Delegates

A method can be assigned to a delegate instance dynamically. This is useful for writing plug-in methods.In below example, The SquareData method has a delegate parameter, for specifying a plug-in SquareData.

 public delegate int delegateSquare(int x);
class Util
{
 public static void SquareData(int[] arr, delegateSquare obj)
 {
 for (int i = 0; i < arr.Length; i++)
 arr[i] = obj(arr[i]);
 }
}
 class demo
{
 static void Main()
 {
 int[] arr = { 1, 2, 3 };
 Util.SquareData(arr, Square); // Dynamically hook in Square
 foreach (int i in arr)
 Console.Write(i + " "); // 1 4 9
 }
 static int Square(int x)
 {
 return x * x;
 }
} 

Types of Delegates

Single cast Delegate

A single cast delegate holds the reference of only single method. Above created delegate are single cast delegate.

Multi cast Delegate

A delegate which holds the reference of more than one method is called multi cast delegate. A multicast delegate only contains the reference of methods which return type is void. The + and += operators are used to combine delegate instances.

 MyDelegate d = Method1;
d = d + Method2;
//short hand for above statement
d += Method2; 

Now, Invoking d will call both methods - Method1 and Method2. Methods are invoked in the order in which they are added.

The - and -= operators are used to remove a method from the delegate instances.

 d -= Method1; 

Now, Invoking d will invoke only Method2.

Multicast delegate example

 delegate void Delegate_Multicast(int x, int y);
class demo
{
 static void Method1(int x, int y)
 {
 int z=x+y;
 Console.WriteLine("Method1 is called");
 Console.WriteLine("\n Sum is : {0}",z);
 }
 static void Method2(int x, int y)
 {
 int z=x+y;
 Console.WriteLine("\n Method2 is called");
 Console.WriteLine("\n Sum is : {0}",z);
 }
 public static void Main() 
 Delegate_Multicast dmulti = Method1;
 dmulti += Method2;
 dmulti(1, 2); // Method1 and Method2 are called
 dmulti -= Method1;
 dmulti(2, 3); // Only Method2 is called
 }
}
Output:
Method1 is called
Sum is : 3
Method2 is called
Sum is : 5 

Note

  1. Delegates are immutable in nature, so when you call += or -= , a new delegate instance is created and it assign to the existing delegate instance.

  2. All delegate are implicitly derived from System.MulticastDelegate, class which is inherit from System.Delegate class.

  3. Delegate types are all incompatible with each other, even if their signatures are the same.

     delegate void D1();
    delegate void D2(); 
    ...
    D1 d1 = Method1;
    D2 d2 = d1; // Compile-time error
    D2 d2 = new D2 (d1); // correct 
  4. Delegate instances are considered equal if they have the reference of same method.

    delegate void D(); 
    ... 
    D d1 = Method1;
    D d2 = Method1;
    Console.WriteLine (d1 == d2); // True 
  5. Multicast delegates are considered equal if they reference the same methods in the same order.

  6. Delegates are used in event handling.

What do you think?

In this article I try to explain the delegates and its types with example. I hope after reading this article you will be able to understand delegates. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.

YOU MIGHT LIKE
Free Interview Books
 
COMMENTS (0)
14 DEC
ASP.NET MVC with AngularJS Development (online)

MON-FRI 07:30 AM- 09:00 AM IST

Know More
5 DEC
AngularJS Development (online)

Mon - Fri     6:30 AM-7:30 AM IST

3 DEC
AngularJS Development (offline)

SAT,SUN     11:00 AM-12:30 PM IST

3 DEC
MEAN Stack Development (offline)

Sat, Sun     (09:30 AM-11:00 AM IST)

26 NOV
ASP.NET MVC with AngularJS Development (offline)

(SAT,SUN)     03:30 PM-05:00 PM IST

24 NOV
ASP.NET MVC with AngularJS Development (online)

MON-FRI     09:30 PM-11:00 PM IST

12 NOV
ASP.NET MVC with AngularJS Development (offline)

SAT,SUN     08:00 AM-09:30 AM

3 NOV
ASP.NET MVC with AngularJS Development (online)

MON-FRI     07:30 AM-09:00 AM IST

25 OCT
.NET Development (offline)

Mon-Fri     9:00 AM-11:00 AM IST

BROWSE BY CATEGORY
 
RECENT ARTICLES
SUBSCRIBE TO LATEST NEWS
 
LIKE US ON FACEBOOK
 

Professional Speaks

+