An Overview of Delegate In C#

What is delegate?

 

A delegate is a type-safe function pointer that holds the reference to a function. The signature of the delegate must match the signature of the function that it points to, else you will get a compilation error. Delegate is type-safe because it points to a function and holds the signature of the function.

 

How to declare delegates in C#?

 
A delegate is similar to a class. We can create an instance of a delegate, however, while creating the instance, we have to pass the function name as a parameter to the delegate constructor. All delegates are implicitly derived from the System.Delegate class.

Syntax

Delegate<return type><delegate name><parameter list>

  1. Delegate void HelloWorld(string message)  

What are the different types of Delegates?

Single Delegate

The delegate that can call a single method is called a single delegate.
  1. using System;  
  2. namespace Delegate_Demo  
  3. {  
  4.     public delegate void Message(string msg);  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             Message msg = new Message(PrintMessage);  
  10.             msg("Welcome to delegate");  
  11.             Console.ReadLine();  
  12.         }  
  13.         public static void PrintMessage(string message)  
  14.         {  
  15.             Console.WriteLine(message);  
  16.         }  
  17.     }  
  18. }  

Multicast Delegate

A delegate which calls multiple methods is called Multicast Delegate. The + (plus) and – (minus) operators are used to subscribe and unsubscribe. A Multicast delegate is a delegate that has references to more than one functions. When you invoke a multicast delegate, all the functions the delegate is pointing to, are invoked.
  1. using System;  
  2. namespace Delegate_Demo  
  3. {  
  4.     class MulticastDelegate  
  5.     {  
  6.         public delegate void PrintMessage();  
  7.         static void Main()  
  8.         {  
  9.             //PrintMessage msg1, msg2, msg3, msg4;  
  10.             //msg1 = new PrintMessage(Greeting);  
  11.             //msg2 = new PrintMessage(Wish);  
  12.             //msg3 = new PrintMessage(Suggesion);  
  13.             //msg4 = msg1 + msg2 + msg3;  
  14.             //msg4();  
  15.             //Console.ReadLine();  
  16.   
  17.             //PrintMessage msg = new PrintMessage(Greeting);  
  18.             //msg += Wish;  
  19.             //msg += Suggesion;  
  20.             //msg();  
  21.             //Console.ReadLine();  
  22.   
  23.             PrintMessage msg = new PrintMessage(Greeting);  
  24.             msg += Wish;  
  25.             msg -= Suggesion;  
  26.             msg();  
  27.             Console.ReadLine();  
  28.         }  
  29.   
  30.         public static void Greeting()  
  31.         {  
  32.             Console.WriteLine("Good Morning");  
  33.         }  
  34.         public static void Wish()  
  35.         {  
  36.             Console.WriteLine("happy Wedding Anniversary");  
  37.         }  
  38.         public static void Suggesion()  
  39.         {  
  40.             Console.WriteLine("You should take your wife for a tour.");  
  41.         }  
  42.     }  
  43. }  

Generic Delegate

Generic delegate does not require an instance to be defined.

What are the types of generic delegates?

There are three types of generic delegates

  • Action
  • Func
  • predicate

Action is a delegate (pointer) to a method, that takes zero, one, or more input parameters, but does not return anything.

  1. using System;  
  2. namespace Delegate_Demo  
  3. {  
  4.     class ActionDelegate  
  5.     {  
  6.         static void Main()  
  7.         {  
  8.             //Action<int> yourAge = Age;  
  9.             //yourAge(30);  
  10.   
  11.             //Action<int> yourAge = age => Console.WriteLine(age);  
  12.             //yourAge(30);  
  13.   
  14.             Action<int> yourAge = new Action<int>(Age);  
  15.             yourAge(30);  
  16.             Console.ReadLine();      
  17.         }  
  18.   
  19.         public static void Age(int age)  
  20.         {  
  21.             Console.WriteLine("Your Age is:"+ age);  
  22.         }  
  23.     }   
  24. }  

Func is a delegate (pointer) to a method, that takes zero, one, or more input parameters, and returns a value (or reference).

  1. using System;  
  2. namespace Delegate_Demo  
  3. {  
  4.     public delegate int Marks(int a,int b,int c,int d, int e, int f);  
  5.     class FunDelegate  
  6.     {  
  7.         static void Main()  
  8.         {  
  9.             Marks marks = CalculateMarks;             
  10.             int Result = marks(80, 75, 58, 72, 89, 60);  
  11.             Console.WriteLine("Total Marks:" + Result);  
  12.             Console.ReadLine();  
  13.         }  
  14.   
  15.         public static int CalculateMarks(int hindi,int english, int physics, int chemistery, int biology, int math)  
  16.         {  
  17.             return hindi + english + physics + chemistery + biology + math;  
  18.         }         
  19.     }  
  20. }  

Predicate is a special kind of Func often used for comparisons.

  1. using System;  
  2.   
  3. namespace Delegate_Demo  
  4. {  
  5.     class Predicate  
  6.     {  
  7.         static void Main()  
  8.         {  
  9.             Predicate<int> voter = IsEligibleForVote;  
  10.             bool result=voter(18);  
  11.             Console.WriteLine("Eligible for voting: " + result);  
  12.             Console.ReadLine();  
  13.         }  
  14.   
  15.         public static bool IsEligibleForVote(int age)  
  16.         {  
  17.             if (age >= 18)  
  18.                 return true;                
  19.             else  
  20.                 return false;  
  21.         }  
  22.     }  
  23. }  

We use delegates when -

  • An event design pattern is used.
  • It is desirable to encapsulate a static method.
  • The caller has no need to access other properties, methods, or interfaces on the object implementing the method.
  • An easy composition is desired.
  • A class may need more than one implementations of the method.


Similar Articles