#553 – Anonymous Methods as Static or Instance Methods

An anonymous method that is declared within an instance method is considered itself to be an instance method of the class in which it was defined.  This means that it can make use of instance data within the class.

In the example below, an anonymous method is declared within the DogInteractions.BarkAtNeighbor method.  Since this is an instance method, the body of the anonymous method can make use of the numBarks instance variable.

    public class DogInteractions
    {
        private int numBarks = 0;

        public void BarkAtNeighbor(Dog d, string neighbor)
        {
            // Delegate passed into the Bark method,
            //   which will then invoke it.
            d.Bark(
                delegate(string barkSound)
                {
                    numBarks++;
                    Console.WriteLine("Bark #{0} - Hey {1}: {2}", numBarks, neighbor, barkSound);
                });
        }
    }

Similarly, if the anonymous method was declared within a static method, it would be considered itself to be static and could not make use of instance data within the class.