Consider the following code in C++:
This code actually compile and the output is the following:
The important thing to notice here is that in C++ is possible to declare a variable with the same name in a nested block.
“A name declared in a block is local to that block; it has block scope. Its potential scope begins at its point of declaration and ends at the end of its block. A variable declared at block scope is a local variable.”
In C# this is not possible. The following code does not compile:
In C# you cannot declare another local variable with the same name in the current block or in any nested blocks. In addition, the variable scope extends in both directions throughout its code block.
Even the following code does not compile:
I would say that the restriction imposed by C# is good and avoid unexpected behaviours in some situations. It also encourages to use meaningful names for variables avoiding to reuse the same variable for different purposes.
However, the following C# code compiles:
This because the two blocks are not related to each others. They are not part of the same chain of nested blocks. This is good because there is a typical situation when you like to reuse the same variable name in loops.
This code compiles: