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:
I have the following two questions:
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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With