I just ran into really weird C # behavior and Id would be glad if anyone could explain this to me.
Let's say I have the following class:
class Program { static int len = 1; static void Main(string[] args) { Func<double, double> call = len => 1; len = 1;
As I understand it, in the comment line I have the following objects in my field of view: len variable and call . Inside lambda, I have a local parameter parameter len and Program.len .
However, after declaring such a lambda, I can no longer use the len variable in the Main . I have to either reference it, or Program.len or rewrite lambda as anyOtherNameBesidesLen => 1 .
Why is this happening? Is this the correct language behavior, or has Ive encountered a language error? If this is correct behavior, how is language architecture justifying it? Why is it ok for a lambda capture variable to work with code outside of lambda?
Edit: Alessandro D'Andria has some good examples (number 1 and 2 in his comment).
edit2: This code (equal to the one I wrote at the beginning) is illegal:
class Program { static int len = 0; static void Main(string[] args) { { int len = 1; } int x = len; } }
This code, although it has exactly the same visibility structure, is completely legal:
class Other { static int len = 0; class Nested { static void foo() { int len = 1; } static int x = len; } }
c # lambda
Dantragof
source share