Understanding C# Anonymous Methods
It's possible to associate an event directly to a block of code statements at the time of event registration. Formally, such code is termed an anonymous method.
Car c1 = new Car("SlugBug", 10, 100);
// Register event handlers as anonymous methods
c1.AboutToBlow += delegate { Console.WriteLine("Eeek! Going too fast!"); };
c1.AboutToBlow += delegate (object sender, CarEventArgs e)
{
Console.WriteLine(e.msg);
};
c1.Exploded += delegate(object sender, CarEventArgs e)
{
Console.WriteLine(e.msg);
};
for(int i = 0; i < 6; i++)
{
c1.Accelerate(20);
}Note: The final curly bracket of an anonymous method must be terminated by a semicolon. If you fail to do so, compilation error:
The basic syntax of an anonymous method matches the following pseudocode:
SomeType t = new SomeType();
t.SomeEvent += delegate (optionallySpecifiedDelegateArgs)
{
/*
Statements
*/
};Strictly speaking, you are not required to receive the incoming arguments sent by a specific event.
Accessing Local Variables
Anonymous methods, they can access the local variables of the method that defines them. Such variables are termed "outer variables" of the anonymous method.
- An anonymous method cannot access ref or out parameters of the defining method.
- An anonymous method cannot have a local variable with the same name as a local variable in the outer method.
- An anonymous method can access instance variables (or static variables) in the outer class scope.
- An anonymous method can declare local variables with the same name as outer class member variables.
int aboutToBlow = 0;
c1.AboutToBlow += delegate
{
aboutToBlow++;
};
for(int i = 0; i < 6; i++)
{
c1.Accelerate(20);
}
Console.WriteLine(aboutToBlow);Using static with Anonymous Methods
Anonymous methods can also be marked as static to preserve encapsulation and ensure that the method cannot introduce any side effects into the containing code.
int aboutToBlow = 0;
c1.AboutToBlow += static delegate
{
// Compiler error!
aboutToBlow++; // Remove this is OK
Console.WriteLine("Eeek!");
};Discard with Anonymous Methods
There must be 2 or more discards used with the anonymous method to be treated as discards.
Func<int, int, int> constant = delegate (int _, int _) { return 42; };
Console.WriteLine(constant(3,4));