Created
February 14, 2013 20:33
-
-
Save yetanotherchris/4956144 to your computer and use it in GitHub Desktop.
C# delegate examples
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
public class DelegateExample | |
{ | |
private delegate bool myDelegate(string s); | |
private bool IsBob(string name) | |
{ | |
return name == "bob"; | |
} | |
public void Run() | |
{ | |
// | |
// This is just to show the Func's equivalent delegate way of doing things, which is less code here, | |
// but you end up repeating delegates everywhere. | |
// | |
// Syntax: | |
// - method1. is C# 3.0 | |
// - method2. is C# 2.0 | |
// - method3. is C# 1.0 | |
// - method4. is C# 2.0+ | |
// | |
myDelegate method1 = ((name) => name == "bob"); | |
myDelegate method2 = delegate(string name) | |
{ | |
return name == "bob"; | |
}; | |
myDelegate method3 = new myDelegate(IsBob); | |
myDelegate method4 = IsBob; // Shorthand for the above | |
bool isBob1 = method1("bob"); | |
bool isBob2 = method2("bob"); | |
bool isBob3 = method3("bob"); | |
bool isBob4 = method4("bob"); | |
Console.WriteLine(isBob1); | |
Console.WriteLine(isBob2); | |
Console.WriteLine(isBob3); | |
Console.WriteLine(isBob4); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment