Multicast Delegate in C# with Example

Rating: 5 - 1 Votes

Multicast Delegate in C# with Example

Multicast Delegate in C# with Example

Multicast Delegate in C# with Example

Multicast delegate contains reference to more than one method or it could be a combination of other delegates, which is also known as delegate chaining.  In delegate chaining, whenever you invoke your multicast delegate, all the delegates in its chain will be invoked automatically.  Before adding any more delegates to the chain, you must make sure that they should match in terms of signature and return type.  To add a delegate you can use +  or += sign and to remove a delegate from the chain, you can use – or -= sign.  Multicast delegate contains an invocation list, which means all the delegates in the chain will be invoked in the same order in which you will add them to the chain.

 Output:

Print A
Print C
Print B
Print A
Press any key to continue . . .

Instead of creating an instance of a delegate and then adding it to the chain, you can directly add or remove methods from a delegate.   This means no more further delegate instances are required.  Just create one instance of delegate and add or remove methods using + or – sign, or += or -= sign.  All the methods will be invoked in the same order in which you will add them to the delegate.

 Output:

Print A
Print C
Print B
Press any key to continue . . .

As we know, a delegate can also have a different return type other than void.  This means your delegate can also return some value after invoking the delegate.  You are good to go as long as you are not using multicast delegate.  But in case of multicast delegate, there is a confusion what value will be returned after invoking 10 or 15 methods in the invocation list?  In this case, your delegate will return the value depending upon the last method in the invocation list.  A good example is given below.

 Output:

My name is John Marks.
Press any key to continue . . .