Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda Expressions : Compiler Behaviour

Tags:

c#

lambda

Well I am going through the 'Lambda Expressions' topic (Chapter 17; Delegates, C# Syntactical Sugar for Delegates). Jeffery states that the C# compiler creates a new non-static class in the background that has the following:

  1. Fields to store all the local variables that have been accessed in the Lambda Expression.
  2. A method whose body contains the Lambda Expression and whose signature/return type matches the delegate for which the Lambda Expressin has been used.

I have the following two questions:

  1. I did a little debugging myself and saw that if the Lambda Expression modifies the value of a local variable(defined in a method the lambda Expresison is being used in), the new value is reflected outside the expression body too. How is this possible considering the expression is actually in a different class?

  2. Why does the emitted class need to be non-static when the same can be done by Static class perfectly?

I hope this is not a very simple concept that I am unable to comprehend.

Let me know if I need to provide more details.

like image 491
astraldust Avatar asked Mar 14 '13 09:03

astraldust


1 Answers

First of all i had a similar question, a few days ago.

Closure captured variable modifies the original as well

Second, what is the point of making it a static class? Only one object is created anyway, and that object does not have to live troughout the application lifetime.

the new value is reflected outside the expression body too. How is this possible considering the expression is actually in a different class.

The thing is that the same object is being referenced both by the anonymus method, as well as the local variable outside the anonymus method, so it does not matter from where you change it, you change the same thing.

Also, the answer provided by Tim Goodman in the question i linked to, shows you what to do, in order to avoid changes being reflected everywhere, by creating a new object inside your anonymus method.

like image 173
Freeman Avatar answered Sep 21 '22 20:09

Freeman