Skip to content

Instantly share code, notes, and snippets.

@ChrisMoney
Last active September 30, 2015 22:22
Show Gist options
  • Save ChrisMoney/948f480212304e07e903 to your computer and use it in GitHub Desktop.
Save ChrisMoney/948f480212304e07e903 to your computer and use it in GitHub Desktop.
C# - Delegate, similar to an anonymous function
//Define the delegate
public delegate int Calculate (int value1, int value2);
//a method, that will be assigned to delegate objects having the EXACT signature of the delegate
public int add(int value1, int value2)
{
return value1 + value2;
}
//a method, that will be assigned to delegate objects having the EXACT signature of the delegate
public int sub( int value1, int value2)
{
return value1 - value2;
}
//creating the class which contains the methods that will be assigned to delegate objects
MyClass mc = new MyClass();
//delegate object takes the original method as a parameter
Calculate add = new Calculate(mc.add);
Calculate sub = new Calculate(mc.sub);
//using the delegate objects to call the assigned methods
Console.WriteLine("Adding two values: " + add(10, 6));
Console.WriteLine("Subtracting two values: " + sub(10,4));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment