About lambda expressions accessing external variables

Source: Internet
Author: User

The book C # advanced programming mentions that using lambda expressions to access external variables of lambda expressions blocks is a good function (similar to closures in JS ). However, it is very dangerous to use it correctly.

For example

Int someval = 5;

Fun <int, int> F = x => X + someval;

Console. writeline (f (3 ));

Our expression is intended to return the result of a number x + 5. Therefore, the result of F (3) should be 3 + someval = 8.

However, if someval value is accidentally modified in the future, unexpected results will appear.

For example:

Someval = 7;

Console. writeline (f (3 ));

The printed result is 10.

Especially when Lambda is called through multiple threads, we may not know the value of someval at this time, resulting in unpredictable results, so we should use it with caution.

 

So what is the principle of using external variables in lambda expressions.

Originally, when running a Lambda expression, the compiler creates an anonymous class, which can pass external variables through constructors. The parameters of this constructor depend on the number of variables passed in externally. For the above expression, the anonymous class is as follows:

 

Public class anonymousclass {

Private int someval;

Public anonymousclass (INT someval) {This. someval = someval ;}

Public int anonymous (int x) {return x + someval ;}

}

In this way, we can understand why lambda expressions can use external variables.

About lambda expressions accessing external variables

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.