Skip to content

Instantly share code, notes, and snippets.

@jmsevold
Last active May 25, 2016 18:19
Show Gist options
  • Save jmsevold/804bb0d450e954c37441f10b0bfc3ab4 to your computer and use it in GitHub Desktop.
Save jmsevold/804bb0d450e954c37441f10b0bfc3ab4 to your computer and use it in GitHub Desktop.
using System;
public delegate void SimpleDelegate(int a,int b);
class Class1
{
// two methods handlers with the same signature as the delegate
static void product(int i,int j)
{
Console.WriteLine(i*j);
}
static void sum(int i, int j)
{
Console.WriteLine(i + j);
}
/*
The method takes a delegate and calls it with two numbers.
It doesn't know which method it will delegate the arguments to, or how that data will be operated on,
and only knows the method must have a matching signature.
This is a single point of reference to invoke multiple subscribers.
*/
static void takesDelegate(SimpleDelegate del)
{
del(3,2);
}
static void Main(string[] args)
{
// We've created two delegate objects, and passed them different handlers that both are called in the same place - the method takesDelegate.
SimpleDelegate delObj1 = new SimpleDelegate(product);
SimpleDelegate delObj2 = new SimpleDelegate(sum);
takesDelegate(delObj1);
takesDelegate(delObj2);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment