In this chapter you will learn:
- What is multicast delegate?
- How to initialize c# multicast delegates?
- Programming Example
What is Multicast Delegate?
Multicast Delegate is an extension of normal delegates. It combines more than one method at a single moment of time.
Important Fact about Multicast Delegate
- In Multicasting, Delegates can be combined and when you call a delegate, a whole list of methods is called.
- All methods are called in FIFO (First in First Out) order.
- + or += Operator is used for adding methods to delegates.
- – or -= Operator is used for removing methods from the delegates list.
Programming Example
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Multicast_Delegates { class TestDeleGate { public delegate void ShowMessage(string s); public void message1(string msg) { Console.WriteLine("1st Message is : {0}", msg); } public void message2(string msg) { Console.WriteLine("2nd Message is : {0}", msg); } public void message3(string msg) { Console.WriteLine("3rd Message is : {0}", msg); } } class Program { static void Main(string[] args) { TestDeleGate td = new TestDeleGate(); TestDeleGate.ShowMessage message = null; message += new TestDeleGate.ShowMessage(td.message1); message += new TestDeleGate.ShowMessage(td.message2); message += new TestDeleGate.ShowMessage(td.message3); message("Hello Multicast Delegates"); message -= new TestDeleGate.ShowMessage(td.message2); Console.WriteLine("----------------------"); message("Message 2 Removed"); Console.ReadKey(); } } }
Output
1st Message is : Hello Multicast Delegates
2nd Message is : Hello Multicast Delegates
3rd Message is : Hello Multicast Delegates
----------------------
1st Message is : Message 2 Removed
3rd Message is : Message 2 Removed
Explanation
This is the very basic example of Multicast delegates.
- Delegates Created
public delegate void ShowMessage(string s);
- Created 3 functions
public void message1(string msg) public void message2(string msg) public void message3(string msg)
- Created Delegate's Object in Main method
TestDeleGate.ShowMessage message = null;
- All the methods are added to delegates object.
message += new TestDeleGate.ShowMessage(td.message1); message += new TestDeleGate.ShowMessage(td.message2); message += new TestDeleGate.ShowMessage(td.message3);
Print Delegatesmessage("Hello Multicast Delegates");
- Remove
message2(string msg)
from delegatesmessage -= new TestDeleGate.ShowMessage(td.message2);
Summary
In this chapter you learned about multicast delegates in c#. In the next chapter you will learn very important topics in c# - Event Handling.