Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
C# delegate examples
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
You can’t perform that action at this time.