Anonymous Methods Have Access to Local Variables Where They Are Declared

When you declare an anonymous method, the body of the method has access to any formal parameter that you declared as part of the anonymous method declaration.  For example, in the code fragment before, the body of the method has access to the s parameter.
1
2
StringHandlerDelegate del1 =
    delegate (string s) { Console.WriteLine(s); };
The body of an anonymous method can also make use of any variables visible within the scope where it is defined. In the example below, the method makes use of the local variable rudeNeighbor.  The Bark method accepts a delegate and then invokes that delegate, passing back the actual bark noise that the dog makes.
1
2
3
4
5
6
7
8
static void Main()
{
    string rudeNeighbor = "Paul";
 
    Dog d = new Dog("Jack", 17);
 
    d.Bark(delegate(string s) { Console.WriteLine("Hey {0}: {1}", rudeNeighbor, s); });
}
For completeness, here is the body of the Dog.Bark method:


1
2
3
4
public void Bark(BarkAtDelegate barkMethod)
{
    barkMethod("Grrrr");
}