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

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.

        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:

        public void Bark(BarkAtDelegate barkMethod)
        {
            barkMethod("Grrrr");
        }
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

7 Responses to #552 – Anonymous Methods Have Access to Local Variables Where They Are Declared

  1. zzfima says:

    The name of this variables in context of delegate: captured variable. See here http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx

  2. Joe says:

    Where is the definition of BarkAtDelegate?

  3. A word of caution here. I ran into an issue when storing a delegate (to be executed later) that used a variable in scope. When building a delegate in a loop, the most recent value of that variable is used by the delegate at execution time. For example, this code will result in John being growled at 3 times instead of each of the neighbors being growled at:

    static void Main()
    {
    string[] rudeNeighbors = new string[] { “Paul”, “Ringo”, “John” };

    Dog[] dogs = new Dog[] { new Dog(), new Dog(), new Dog() };

    int i = 0;
    foreach (string rudeNeighbor in rudeNeighbors)
    {
    dogs[i].BarkMethod = delegate { Console.WriteLine(“Hey {0}: {1}”, rudeNeighbor, “Grrrr”); };
    i++;
    }

    foreach(Dog dog in dogs)
    {
    dog.Bark();
    }
    }

    class Dog
    {
    public BarkAtDelegate BarkMethod;

    public void Bark()
    {
    BarkMethod();
    }

    public delegate void BarkAtDelegate();
    }

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: