Skip to content

Instantly share code, notes, and snippets.

@jmsevold
Last active June 3, 2016 17:37
Show Gist options
  • Save jmsevold/438f77ae3fc9d355af988531bb87fb15 to your computer and use it in GitHub Desktop.
Save jmsevold/438f77ae3fc9d355af988531bb87fb15 to your computer and use it in GitHub Desktop.
/*
If you know the four steps of delegate creation and usage, you know 90% of the steps
involved to create and call a multicast delegate. As a refresher, the four steps are:
1. Declare a delegate.
2. Instantiate the delegate.
3. Store an appropriate method in the delegate instance (anonymous method, named method, or lambda)
4. Call the delegate, passing the appropriate arguments.
A multi-cast delegate begins at step 2 above, and continues to steps 3 and 4 with two differences:
- Rather than storing a single method, you store a delegate.
- Rather than storing a single method in this manner myDelegate = appropriateMethod, you use + operator
to store as many delegates as you want.
These delegates being stored with + should be in the state found at step 3: They have
been instantiated and have already stored an appropriate method. Think of them as fully-loaded and ready to go- they
just need to be given arguments and called, which is what the multicast delegate holding them will do. Give the multicast
delegate fully loaded delegates, then pass the argument(s) to the MCD and call it, which will call all the delegates
its holding.
*/
using System;
public class Program
{
delegate void CustomDelegate(string name);
public static void Main()
{
CustomDelegate multicastDelegate;
CustomDelegate delHi = (name) => Console.WriteLine("Hi {0}!", name);
CustomDelegate delBye = (name) => Console.WriteLine("Bye {0}!", name);
CustomDelegate delInsult = (name) => Console.WriteLine("Screw you {0}!", name);
multicastDelegate = delHi + delBye;
multicastDelegate += delInsult;
multicastDelegate("bobby");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment