Skip to content

Instantly share code, notes, and snippets.

@dnasca
Created March 17, 2015 06:35
Show Gist options
  • Select an option

  • Save dnasca/f72ad5959562accf60df to your computer and use it in GitHub Desktop.

Select an option

Save dnasca/f72ad5959562accf60df to your computer and use it in GitHub Desktop.
using System;
/* Multicast Delegates
*
* A multicast delegate is a delegate that has a reference to more than one function.
* When you invoke a multicast delegate, all of the functions the delegate is pointing to are invoked.
*
* There are 2 approaches to create a multicast delegate (multiple instances, or the same instance)
* 1. + or += to register a method with the delegate (SEE APPROACH ONE)
* 2. - or -= to un-register a method with a delegate (SEE APPROACH TWO)
*
* Important: A multicast delegate invokes the methods in the invocation list in the same order in which they are added
*
* If the delegate has a return type other than void, and if the delegate is a multicast delegate, only the value of the last
* invoked method will be returned.
*
* If the delegate has an output parameter, the value of the output parameter will be the value assigned by the last method
*
* !!Interview Question!!
* Q. Where do you use multicast delegates?
* A. Multicast delegates make implementations of observer design patterns simple. (Observer pattern design is also called publish/subscribe pattern)
*
*/
//APPROACH ONE
/*
public delegate void SampleDelegate();
public class Program
{
public static void Main()
{
SampleDelegate del1, del2, del3, del4;
del1 = new SampleDelegate(SampleMethodOne);
del2 = new SampleDelegate(SampleMethodTwo);
del3 = new SampleDelegate(SampleMethodThree);
del4 = del1 + del2 + del3; //delegate four is now pointing to all three methods
del4(); //This is our multicast delegate
Console.ReadKey();
}
public static void SampleMethodOne()
{
Console.WriteLine("SampleMethodOne invoked");
}
public static void SampleMethodTwo()
{
Console.WriteLine("SampleMethodTwo invoked");
}
public static void SampleMethodThree()
{
Console.WriteLine("SampleMethodThree invoked");
}
}
*/
//APPROACH TWO - using the same instance of a delegate to point to multiple methods
public delegate void SampleDelegate(out int integer);
public class Program
{
public static void Main()
{
SampleDelegate del = new SampleDelegate(SampleMethodOne);
del += SampleMethodTwo;
int DelegateOutputReturnValue = 0;
del(out DelegateOutputReturnValue);
Console.WriteLine("DelegateReturnedValue = {0}", DelegateOutputReturnValue); //if the delegate has an out parameter, the value of the
//output parameter will be the value assigned by the last invoked method
//in this case, it will return the output of SampleMethodTwo
Console.ReadKey();
}
public static void SampleMethodOne(out int number)
{
number = 1;
}
public static void SampleMethodTwo(out int number)
{
number = 2;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment