C# Anonymous function-scope

anonymous-function, c#, lambda

Solution

Actually, even in javascript it isn't entirely disconnected; javascript allows lexical closures - so without the `var`, the old value of `foo` should still be available.

The difference is that javascript chooses to allow you to re-declare the name with a different meaning (in the inner scope). C# chooses not to.

I find the C# version less easy to get confused about! In particular when code (further down in the method) expects to be talking about the "old" variable, and suddenly it starts looking at the "new" one.

Problem

``` var foo = "bar"; new Func<String>(() => { var foo = ""; // This can't be done in C#. Why is that? /* In JavaScript, this is perfectly valid, since this scope (the anonymous function) is disconnected from the outer scope, and any variable declared within this scope will not affect variables in the outer scope */ })() ```

Original source