#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.

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: