Delegates In C# Explained

Introduction 

 
In this article, we look at delegates and how to multicast them. 
 
Before we understand delegates, we need to know some of the basic stuff, such as the Reference type variable, which holds the reference of memory address instead of value.
 
For example:
  1. Person objPerson = new Person(); 
Here, objPerson is a reference variable that is pointing towards the Person's object.
 
We know that we can hold the reference of an object, but how cool it would be if we can hold a reference to a method.
 
That's where delegate comes into the picture.
 
A delegate holds a reference to the methods, kind of a function pointer in C++.
 
But what is the purpose?
 
The answer is to ensure which method is to be called when an event is triggered plus the reference can be changed at runtime.

Enough talk: let's see its syntax.
 
There are 3 steps involved:
 
Declaration
 
Syntac - <Access-Modifier> delegate <return type> <delegate-name> <parameter list>
  1. //Step 1 : Declaring a delegate  
  2. public delegate int MyDelegate (string s); 
Create delegate instances:
  1. //Step 2 : Creating a delegate instances  
  2. CheckSmartPhone isThisSmartPhone = new CheckSmartPhone(GetIPhoneX); 
Invoking a method through the delegate instance:
  1. //Step 3 : calling the methods using the delegate objects  
  2. bool checkSmartPhone = isThisSmartPhone("IPhoneX"); 
Here, GetIPhoneX is a Method, which must match exact same signature as defined in the delegate's declaration:
  1. private static bool GetIPhoneX(string name)  
  2.        {  
  3.             if (name == "IPhoneX")  
  4.                return true;  
  5.            else  
  6.                return false;  
  7.        } 
Note
Static is only because we are going to call this method inside the Main method.

Final code
  1. class Program  
  2.    {  
  3.        //Step 1 : Declaring a delegate  
  4.        public delegate bool CheckSmartPhone(string smartPhoneName);  
  5.        static void Main(string[] args)  
  6.        {  
  7.            //Step 2 : Creating a delegate instances  
  8.            CheckSmartPhone isThisSmartPhone = new CheckSmartPhone(GetIPhoneX);  
  9.   
  10.            //Step 3 : calling the methods using the delegate objects  
  11.            bool checkSmartPhone = isThisSmartPhone("IPhoneX");  
  12.            if (checkSmartPhone)  
  13.            {  
  14.                System.Console.WriteLine("It is a smart phone!!!");  
  15.            }  
  16.            else  
  17.            {  
  18.                System.Console.WriteLine("It is not a smart phone!!!");  
  19.            }  
  20.        }  
  21.   
  22.        private static bool GetIPhoneX(string name)  
  23.        {  
  24.            if (name == "IPhoneX")  
  25.                return true;  
  26.            else  
  27.                return false;  
  28.        }  
  29.    } 
Let's check what the output is:
 
Delegates In C#
 
Now let's see the Multicasting of a Delegate.

Delegate objects can be composed using the "+" operator and decomposed with "-" operator.

Only delegates with the same signature can be composed together.
 
i.e. the same Delegate but different instances can be composed together.

Let's understand this with code.

We will check if smartPhones runs on "IOS" or not.

Rather than calling each method separately, we can simply have 2 delegate instances and concatenating them together.

Here are our two methods, which checks which OS their smartPhone runs on:
  1. private static bool GetIPhoneX(string OS)  
  2.         {  
  3.             if (OS == "IOS")  
  4.                 return true;  
  5.             else  
  6.                 return false;  
  7.         }  
  8.         private static bool GetOnePlus8(string OS)  
  9.         {  
  10.             if (OS == "Android")  
  11.                 return true;  
  12.             else  
  13.                 return false;  
  14.         }  
  15.   
  16. //Step 1 : Declaring a delegate  
  17.         public delegate bool CheckSmartPhone(string OSName);  
  18.           
  19. //Step 2 : Creating a delegate instances  
  20.             CheckSmartPhone areBothRunsOnApple = new CheckSmartPhone(GetIPhoneX);  
  21.             CheckSmartPhone onePlus8 = new CheckSmartPhone(GetOnePlus8);  
  22.   
  23. //concatenating delegate instances  
  24.             areBothRunsOnApple += onePlus8;  
  25.   
  26. //Step 3 : calling the methods using the delegate objects  
  27.             bool check_IOS_Devices = areBothRunsOnApple("IOS");  
  28.               
  29.             if (check_IOS_Devices)  
  30.             {  
  31.                 System.Console.WriteLine("Both runs on IOS!!!");  
  32.             }  
  33.             else  
  34.             {  
  35.                 System.Console.WriteLine("Not all of them runs on IOS!!!");  
  36.             } 
 Delegates In C#
 
Not all of them run on iOS since one of them runs on Android!
   
Let's see another iPhone and check if that works:
  1. private static bool GetIphoneXR(string OS)  
  2.         {  
  3.             if (OS == "IOS")  
  4.                 return true;  
  5.             else  
  6.                 return false;  
  7.         }  
  8.           
  9.         Also make respective changes,  
  10.          //Step 2 : Creating a delegate instances  
  11.             CheckSmartPhone areBothRunsOnApple = new CheckSmartPhone(GetIPhoneX);  
  12.             CheckSmartPhone IphoneXR = new CheckSmartPhone(GetIphoneXR);  
  13.   
  14.             //concatenating delegate instances  
  15.             areBothRunsOnApple += IphoneXR;  
  16.   
  17.             //Step 3 : calling the methods using the delegate objects  
  18.             bool check_IOS_Devices = areBothRunsOnApple("IOS");  
  19.               
  20.             if (check_IOS_Devices)  
  21.             {  
  22.                 System.Console.WriteLine("Both runs on IOS!!!");  
  23.             }  
  24.             else  
  25.             {  
  26.                 System.Console.WriteLine("Not all of them runs on IOS!!!");  
  27.             } 
Let's see the output now:
 
Delegates In C#
 
Perfect, it works.
 
In the same way, you can use minus operators to remove unwanted calls. Let's say our program needs android smartPhone but not in this delegate calls so you can simply remove that with "-" operator. so it won't call the GetOnePlus8 method.
  1. namespace I_Cant_See_Sharp  
  2. {  
  3.       
  4.     class Program  
  5.     {  
  6.         //Step 1 : Declaring a delegate  
  7.         public delegate bool CheckSmartPhone(string OSName);  
  8.         static void Main(string[] args)  
  9.         {  
  10.             //Step 2 : Creating a delegate instances  
  11.             CheckSmartPhone areBothRunsOnApple = new CheckSmartPhone(GetIPhoneX);  
  12.             CheckSmartPhone IphoneXR = new CheckSmartPhone(GetIphoneXR);  
  13.             CheckSmartPhone onePlus8 = new CheckSmartPhone(GetOnePlus8);  
  14.   
  15.             //concatenating delegate instances  
  16.             areBothRunsOnApple += IphoneXR -= onePlus8;  
  17.   
  18.             //Step 3 : calling the methods using the delegate objects  
  19.             bool check_IOS_Devices = areBothRunsOnApple("IOS");  
  20.               
  21.             if (check_IOS_Devices)  
  22.             {  
  23.                 System.Console.WriteLine("Both runs on IOS!!!");  
  24.             }  
  25.             else  
  26.             {  
  27.                 System.Console.WriteLine("Not all of them runs on IOS!!!");  
  28.             }  
  29.               
  30.         }  
  31.   
  32.         private static bool GetIPhoneX(string OS)  
  33.         {  
  34.             if (OS == "IOS")  
  35.                 return true;  
  36.             else  
  37.                 return false;  
  38.         }  
  39.         private static bool GetIphoneXR(string OS)  
  40.         {  
  41.             if (OS == "IOS")  
  42.                 return true;  
  43.             else  
  44.                 return false;  
  45.         }  
  46.         private static bool GetOnePlus8(string OS)  
  47.         {  
  48.             if (OS == "Android")  
  49.                 return true;  
  50.             else  
  51.                 return false;  
  52.         }  
  53.     }     

Delegates In C#
 
It works just fine. Delegate call has removed GetOnePlus8 method call, & only check if IPhoneX & iPhone-XR are compatible with IOS.

Alright, so this is how you can use delegates in C#.

It's a beautiful concept and I hope this article has helped you to gain some insights into delegates behavior.
 
We will learn more about Func, Action & Predicate in the next article.
 
Until then, Sayonara!

Feel free to connect with me @
Happy Coding!