C# Anonymous functions

Michael Roma on Jul 13, 2012

The following is an example of an anonymous function in C#

// define variable outside of function
int outscope = 3;

// define anonymous function that takes a string, bool and return an int
var f = new Func<string, bool, int>((string x, bool b) =>
{
    Console.WriteLine(String.Format(“anon: {0}, {1}, {2}”, x, b, outscope));
    return 0;
});

// call the anonymous function
f.Invoke(“A”, true); 
outscope = 6;
f.Invoke(“b”, false); 
outscope = -9;
f.Invoke(“C”, true);

Results anon: A, True, 3 anon: b, False, 6 anon: C, True, -9