In this blog, I’m explaining the concept of delegate.
A delegate in C# is similar to a function pointer in C or C++. In C#, a delegate is type safe object that can point to another method (or multiple methods) that means a delegate can point to a method, which is having same signature as that of the delegate in the application, which can invoked at later time.
There are three steps in defining and using delegates:
delegate <return type><delegate-name><parameter list>
Consider the following example:
public delegate void DelegateExample (string s)
// Declaration of delegate
public delegate void DelegateExample();
public static void MyMessage() // create a method for delegate
Console.WriteLine("I was called by delegate ...");
public static void Main()
Test t = new Test();
// Instantiation of delegate
DelegateExample simpleDelegate = new DelegateExample(MyMessage); // It the function name
// Invocation of delegate
simpleDelegate(); // call this method
Output is: I was called by delegate ...
In this example, how to a delegate declare, instantiate, and how to call.
Multicast delegate means that they can point to more than one function at a time. Delegates objects can be composed using the “+” operator. Only delegates of the same type can be composed. The "-" operator can be used to remove a component delegate from a composed delegate.
delegate void MulticastDelegateExample(int x, int y); //declare a multicast delegate
public static void AddNum(int p,int q)
Console.WriteLine("Add two numbers :" + (p + q));
public static void MultNum(int p, int q)
Console.WriteLine("Multiply two numbers :" + (p + q));
static void Main(string args)
//create delegate instances
MulticastDelegateExample nc1 = new MulticastDelegateExample(AddNum);
MulticastDelegateExample nc2 = new MulticastDelegateExample(MultNum);
nc = nc1;
nc += nc2;
//calling multicast both method together
nc -= new MulticastDelegateExample(AddNum);
nc(2, 3); //calling only second method MultNum
In this example, there are two methods and create two instances and one
reference of MulticastDelegateExample. Reference assign both instance
and call both method together and after only call second method.