Last active
September 30, 2015 22:22
-
-
Save ChrisMoney/948f480212304e07e903 to your computer and use it in GitHub Desktop.
C# - Delegate, similar to an anonymous function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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