Why can't I declare a variable with the same name in different scopes in C#?
This question already has an answer here:
Not every {}
starts a new scope. The integer declared in the if block is still on the same stack as the function.
From MSDN Compiler Error CS0136
For each occurrence of a given identifier as a simple-name in an expression or declarator, within the local variable declaration space (§3.3) immediately enclosing that occurrence, every other occurrence of the same identifier as a simple-name in an expression or declarator must refer to the same entity. This rule ensures that the meaning of a name is always the same within a given block, switch block, for-, foreach- or using-statement, or anonymous function.
As a second reference, check Variable scope confusion in C# answers which you can find good information in.
You are allowed to use the same variable name in non-overlapping scopes. If one scope overlaps another, though, you cannot have the same variable declared in both. The reason for that is to prevent you from accidentally using an already-used variable name in an inner scope
As @BlackFrog correctly points out, each { }
does not start a new scope. From the C# Language Specification, §3.3:
• Each method declaration, indexer declaration, operator declaration, instance constructor declaration and anonymous function creates a new declaration space called a local variable declaration space . Names are introduced into this declaration space through formal parameters (fixed-parameters and parameter-arrays) and type-parameters. The body of the function member or anonymous function, if any, is considered to be nested within the local variable declaration space. It is an error for a local variable declaration space and a nested local variable declaration space to contain elements with the same name.
(emphasis mine)
链接地址: http://www.djcxy.com/p/53052.html