1

This piece of code produces the error CS0136:

static void Main(string[] args)
{
    foreach (var arg in args) Console.WriteLine(arg); // error in this line (arg is underlined red)
    string arg = "lol";
    Console.WriteLine(arg);
}

Error description according to microsoft:

A local variable named 'var' cannot be declared in this scope because it would give a different meaning to 'var', which is already used in a 'parent or current/child' scope to denote something else.

In this case the compiler Claims that the parameter arg in the foreach loop is already declared. The Problem i have with this is , that i declare the string arg after the foreach loop, so it should work, or am i missing some point. Is some sort of "Optimizing" which rearranges the order of my code?

I understand, that if i would declare it before the foreach loop it would be an error. Furthermore i know that i could name it diffently. But i want to understand it.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194

1 Answers1

1

The Problem i have with this is , that i declare the string arg after the foreach loop, so it should work

No, it shouldn't.

The scope of a local variable is the whole block in which it is declared - not just from that point onwards. You can't use it before the point of declaration, but it's still in scope.

From the C# 5 ECMA Standard section 8.7.1:

  • The scope of a local variable declared in a local-variable-declaration (§13.6.2) is the block in which the declaration occurs.

Then (still in 8.7.1):

Within the scope of a local variable, it is a compile-time error to refer to the local variable in a textual position that precedes the local-variable-declarator of the local variable.

...

[Note: The scoping rules for local variables and local constants are designed to guarantee that the meaning of a name used in an expression context is always the same within a block. If the scope of a local variable were to extend only from its declaration to the end of the block, then in the example above, the first assignment would assign to the instance variable and the second assignment would assign to the local variable, possibly leading to compile-time errors if the statements of the block were later to be rearranged.]

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194