(() => { var foo = ""; // This can't be done in C#. Why is that? /* In JavaSc...">

C # Anonymous region function

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 */

})()
+3
source share
3 answers

Actually, even in javascript it is not completely disabled; javascript allows lexical closures - so without the varold value should be available foo.

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

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

+13
source

# . , JavaScript, .

- , closure. , , .

+4

Since the code refers to both characters as "locals", the compiler cannot detect which one you are accessing by simply raising the scope chain (local → member →).

FYI, anonymous methods are compiled as classes and assigned (as properties) to any members / locals they receive as fields.

0
source

Source: https://habr.com/ru/post/1714054/


All Articles