Understanding Delegates in C#

Delegates are a mechanism of indirectly calling methods at runtime. The primary use of delegates in C# programming is for implementing events and the call-back methods.

Important Points About Delegate

  • Delegate is a strongly typed function pointer (just like pointer is there in C++ language).
  • A Delegate is a reference type variable which holds the reference of a method.
  • We can call delegate like methods in C#.
  • Delegates are used to raise the event in class and associated with the event handler.
  • Delegate can be Non-Generic/ Generic.

Types of Delegate

There are two types of delegate.

Note
 

Generics are a kind of parameterized data structure that can work with value type as well as reference type. Using generics we can define the data type at runtime using System.Collections.Generic namespace.

  • Single cast Delegate

    1. Single cast Delegate: A single cast delegate is derived from System.Delagate Class.
    2. It contains reference of only one method at a time.

  • Multi-cast Delegate

    1. Multi-cast Delegate: Multicast Delegate is derived from System.MulticatsDelagate class.
    2. It Creates an invocation list of multiple methods.
    3. In Multicast delegate we create a single delegate that invokes multiple methods.
    4. It holds the reference of multiple methods and it executes all the methods as in calling order.
    5. The multiple method called by delegate should not return any values.

Syntax

< public delegate return Type(void/string) delegate_Name (); >

Or

< public delegate return Type(void/string) delegate_Name <T> (); >

Example

Single Cast Non-Generic/Generic Delegate,

  1. namespace Demo_Delegate  
  2. {  
  3.   
  4.     class Single_Cast  
  5.     {  
  6.          
  7.         //Declare Non-Generic Single cast delegate  
  8.         public delegate void Single_Cast_delegate();  
  9.   
  10.         //Private Method to be called  
  11.         private  static void message()  
  12.         {  
  13.             Console.WriteLine("This Example of Single Cast Non-generic Delegate");  
  14.         }  
  15.         static void Main(string[] args)  
  16.         {  
  17.             //Instance created for Single Cast Delagate  
  18.             Single_Cast_delegate SCD = new Single_Cast_delegate(message);  
  19.   
  20.             //Instance created for Single Cast Generic Delagate  
  21.             Single_Cast_Generic SCG = new Single_Cast_Generic();  
  22.             Mydel<int> my1 = new Mydel<int>(SCG.add);  
  23.             Mydel<string> my2 = new Mydel<string>(SCG.Myname);  
  24.   
  25.          //Calling of Delegate  
  26.             SCD();  
  27.             my1(10, 20);  
  28.             my2("My""Name");  
  29.         }  
  30.   
  31.     }  
  32.   
  33.     //Declare Generic Single cast delegate  
  34.     public delegate void Mydel<T>(T a, T b);  
  35.     class Single_Cast_Generic  
  36.     {  
  37.         public void add(int a, int b)  
  38.         {  
  39.             int Sum = a + b;  
  40.             Console.WriteLine(Sum);  
  41.   
  42.         }  
  43.   
  44.         public void Myname(string firstname, string lastname)  
  45.         {  
  46.             string fn = firstname + " " + lastname;  
  47.             Console.WriteLine(fn);  
  48.   
  49.         }  
  50.     }  
Multicast Non-Generic/Generic Delegate,
  1. namespace Demo_Delegate  
  2. {  
  3.     class MyClass  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {  
  7.             //Instance created for Muticaste Cast Delagate  
  8.             MultiCast_delegate md = new MultiCast_delegate();  
  9.             NonGenericMulticaste NGM = new NonGenericMulticaste(md.FirstMessage);  
  10.               
  11.             // Add another method to the invocation list  
  12.             NGM += new NonGenericMulticaste(md.SecondMessage);  
  13.             NGM("Call Mutliple methods using single Object");  
  14.   
  15.   
  16.             //Instance created for MultiCast Generic Delagate  
  17.             MultiCast_Genericdelegate MG = new MultiCast_Genericdelegate();  
  18.                
  19.             //We can call both method having diffrent type with single delegate  
  20.             GenericMulticaste<int> obj1 = new GenericMulticaste<int>(MG.FirstMessage);  
  21.             obj1 += new GenericMulticaste<int>(MG.Message);  
  22.   
  23.             GenericMulticaste<string> obj2 = new GenericMulticaste<string>(MG.SecondMessage);  
  24.             obj2 += new GenericMulticaste<string>(MG.SecondMessage);  
  25.   
  26.             obj1(100);  
  27.   
  28.             obj2("Call Mutliple Generic methods using single Object");  
  29.   
  30.   
  31.              
  32.         }  
  33.     }  
  34.     //Create a multicate Delegate  
  35.     public delegate void NonGenericMulticaste(string Message);  
  36.     class MultiCast_delegate  
  37.     {  
  38.         public void FirstMessage(string Message1)  
  39.         {  
  40.             Console.WriteLine(Message1);  
  41.         }  
  42.         public void SecondMessage(string Message2)  
  43.         {  
  44.             Console.WriteLine(Message2);  
  45.         }  
  46.     }  
  47.     //Create a multicate Generic Delegate  
  48.     public delegate void GenericMulticaste<T>(T Message);  
  49.     class MultiCast_Genericdelegate  
  50.     {  
  51.         public void FirstMessage(int Number)  
  52.         {  
  53.             Console.WriteLine("Your Number is:"+Number);  
  54.         }  
  55.         public void Message(int Number)  
  56.         {  
  57.             Console.WriteLine("Your Number is:" + Number);  
  58.         }  
  59.         public void SecondMessage(string Generic_Message)  
  60.         {  
  61.             Console.WriteLine(Generic_Message);  
  62.         }  
  63.         public void Second(string Generic_Message)  
  64.         {  
  65.             Console.WriteLine(Generic_Message);  
  66.         }  
  67.     }  
Following are the predefined generic delegates,
  1. public delegate TResult Func<in T, out TResult>(T arg);    
  2. public delegate void Action()    
  3. public delegate bool Predicate<in T>(T obj);  
Example
  1. namespace PreDefinedGenericDelegates  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {  
  7.             //Action Delegate  
  8.             Action<int,int> a = new Action<int,int>(MyClass.sum);  
  9.             a(5, 6);  
  10.             Action<stringstring> b = new Action<stringstring>(MyClass.add);  
  11.             b("Kundan""Jha");  
  12.   
  13.             //Func Delegate  
  14.   
  15.             Func<intintint> ds = new Func<intintint>(MyClass.Multi);  
  16.             Console.WriteLine(ds(45, 65));  
  17.   
  18.             //Predicate Delegate  
  19.             Predicate<string> p = new Predicate<string>(MyClass.IsDate);  
  20.             if (p("01-01-2015"))  
  21.             {  
  22.                 Console.WriteLine("Valid");  
  23.             }  
  24.             else  
  25.             {  
  26.                 Console.WriteLine("Invalid");  
  27.             }  
  28.   
  29.             Console.ReadKey();  
  30.   
  31.         }  
  32.     }  
  33.   
  34.     class MyClass  
  35.     {  
  36.         public static bool IsDate(string date)  
  37.         {  
  38.             DateTime dt;  
  39.             return DateTime.TryParse(date, out dt);  
  40.         }  
  41.   
  42.         public static int Multi(int a, int b)  
  43.         {  
  44.             return a + b;  
  45.         }  
  46.         public static void sum(int num1, int num2)  
  47.         {  
  48.             int sum = num1 + num2;  
  49.             Console.WriteLine(sum);  
  50.   
  51.         }  
  52.         public static void add(string fname, string lname)  
  53.         {  
  54.             string fullname = fname + " " + lname;  
  55.             Console.WriteLine(fullname);  
  56.         }  
  57.     }  
  58. }  
I hope you liked this article. Thank You.
Ebook Download
View all
Learn
View all