Use of Delegate

Why use delegate in C#?

 
Delegate is one of the most incorrectly-interpreted words by developers in C#. Delegate is widely used inside .net framework itself. Let’s go further and break down  that delegate question that every interviewer asks.
 

My Experience with Delegates

 
In my all years of experience I have used delegate several times and noticed that after I am done with development who ever over takes that code from me is not able to grasp that particular delegate logic.
 
If used wisely it can save a lot of time and lines of code but if used in inappropriately it will confuse everyone in the future.
 

Purpose

 
It helps achieve the following,
  1. Encapsulation / Abstraction
  2. Security
  3. Callback
  4. Re-usability
Most common definition of Delegate,
 
“Delegate is a keyword in .net that is used as function pointer” or
 
“Delegate is used for callbacks only”
 
Well nothing is wrong with these definitions but they don't tell you the whole picture.
 
Characteristics
 
Delegate has a few characteristics:
  1. Type safe
  2. Takes method in assignment
Let’s start by an example,
 
First let’s create our Product model
 
We are going to use this model
  1. using System;  
  2.   
  3. namespace Models  
  4. {  
  5.     public class Products  
  6.     {  
  7.         public string ProductName { getset; }  
  8.         public int ProductId { getset; }  
  9.   
  10.     }  
  11. }  
Let’s create and interface
 
General practice to create interface
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace BusinessLayer  
  8. {  
  9.     public interface ICustomer<T>  
  10.     {  
  11.         void Process(T products);  
  12.     }  
  13. }  
Second, inherit this interface in class
  1. using Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace BusinessLayer  
  9. {  
  10.     public class FrequentCustomer : ICustomer<Products>  
  11.     {  
  12.         public void Process(Products product)  
  13.         {  
  14.             Console.WriteLine($"Product Count : 1");  
  15.             Console.WriteLine("--Product Details--");  
  16.             Console.WriteLine($"Name : {product.ProductName} Product Id : {product.ProductId}");  
  17.         }  
  18.     }  
  19. }  
Process is the method which will be called by an anonymous later
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace ServiceCallManager  
  8. {  
  9.     public static class ServiceCaller  
  10.     {  
  11.         public static void Invoke<TService>(Action<TService> action)  
  12.         {  
  13.             Type typ = typeof(TService);  
  14.             TService instance = (TService)Activator.CreateInstance(typ);  
  15.               
  16.             action(instance);  
  17.         }  
  18.     }  
  19. }  
Invoke is the method which takes Action<TService> type argument, in .Net Action delegate's return type is void
 
Why Use Delegate
 
See the summary, it says “encapsulates.
 
Now we all know delegate takes method in assignment (Encapsulates method)
 
Method can be in any form, let’s say anonymous methods.
 
What is the anonymous method?
 
“A method without a name!”
 
Now let’s look into our next class.
  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.           
  6.         IList<Products> products = new List<Products>();  
  7.   
  8.         Products product1 = new Products();  
  9.         product1.ProductName = "Rice";  
  10.         product1.ProductId = 1;  
  11.         products.Add(product1);  
  12.   
  13.         product1 = new Products();  
  14.         product1.ProductName = "Dal";  
  15.         product1.ProductId = 2;  
  16.         products.Add(product1);  
  17.   
  18.         product1 = new Products();  
  19.         product1.ProductName = "Chana";  
  20.         product1.ProductId = 3;  
  21.         products.Add(product1);  
  22.           
  23.         ServiceCaller.Invoke<FrequentCustomer>(x => x.Process(product1));  
  24.   
  25.         Console.WriteLine();  
  26.         Console.ReadKey();  
  27.     }  
  28. }  
  1. ServiceCaller.Invoke<FrequentCustomer>(x => x.Process(product1));  
Remember that the invoke method accepts delegate as argument and delegate encapsulates methods, so here inside Invoke method I am passing an anonymous method which will get invoked when action() is called which executes the anonymous method and calls the Process method of FrequentCustomer class.
 
Let’s go step by step,
  • Breakpoint comes to ServiceCaller.Invoke<FrequentCustomer>(x => x.Process(product1));
  • It goes inside Invoke method of staticServiceCaller class
  • Via reflection we are creating object of ServiceT type (You can ignore this if you don’t understand reflection)
  • At the last line of method action is called with parameter instance; i.e. object of ServiceT type
  • After action (instance) is called breakpoint comes to ServiceCaller.Invoke<FrequentCustomer>(x => x.Process(product1)); and it starts executing the x => x.Process(product1) part only
  • You will notice that x is of type FrequentCustomer

    Why Use Delegate

  • So this part of execution calls the Process method or FrequentCustomer and is also passing local parameter in it.
Now the benefit of delegate here is I am able to use local variable inside method; i.e. product1, which may not be available in other class due to security reasons.
 
Delegate helps me implement Encapsulation, Security, Callback (Obviously), Re-usability and if used wisely, Polymorphism also
 
Thanks for reading. 


Next Recommended Reading How to Use Delegate in ASP.NET using C#