Beware of variable sharing caused by anonymous methods

Source: Internet
Author: User
Tags anonymous new features

anonymous method

The anonymous method is an advanced feature introduced in. NET 2.0, and the word "anonymous" indicates that it can write the implementation inline in a method to form a delegate object without having an explicit method name, such as:

static void Test()
{
  Action<string> action = delegate(string  value)
  {
    Console.WriteLine(value);
  };

  action("Hello  World");
}

But the key to anonymous methods is not just the word "anonymous". The most powerful feature is that the anonymous method forms a closure that can be passed as an argument to another method, but it can also access local variables of the method and other members of the current class. For example:

class TestClass
{
  private void Print(string message)
  {
     Console.WriteLine(message);
  }

  public void Test()
  {
     string[] messages = new string[] { "Hello", "World" };
    int index =  0;

    Action<string> action = (m) =>
    {
       this.Print((index++) + ". " + m);
    };

    Array.ForEach(messages,  action);
    Console.WriteLine("index = " + index);
  }
}

As shown above, in the TestClass test method, the action delegate invokes the private method print in the TestClass class and reads and writes the local variable index in the test method. In addition to the new features of lambda expressions in C # 3.0, the use of anonymous methods has been greatly promoted. However, if used improperly, anonymous methods can easily cause problems that are difficult to discover.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.