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,
- Encapsulation / Abstraction
- Security
- Callback
- 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:
- Type safe
- Takes method in assignment
Let’s start by an example,
First let’s create our Product model
We are going to use this model
using System;
namespace Models
{
public class Products
{
public string ProductName { get; set; }
public int ProductId { get; set; }
}
}
Let’s create and interface
General practice to create interface
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BusinessLayer
{
public interface ICustomer<T>
{
void Process(T products);
}
}
Second, inherit this interface in class
using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BusinessLayer
{
public class FrequentCustomer : ICustomer<Products>
{
public void Process(Products product)
{
Console.WriteLine($"Product Count : 1");
Console.WriteLine("--Product Details--");
Console.WriteLine($"Name : {product.ProductName} Product Id : {product.ProductId}");
}
}
}
Process is the method which will be called by an anonymous later



Amit MohantyPosted Nov 8, 2020, 11:47 PM
Very helpful to the readers.
Rajanikant HawaldarPosted Nov 7, 2020, 11:36 PM
Informative blog