Skip to content

Instantly share code, notes, and snippets.

@yetanotherchris
Created February 14, 2013 20:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yetanotherchris/4956144 to your computer and use it in GitHub Desktop.
Save yetanotherchris/4956144 to your computer and use it in GitHub Desktop.
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