#1,104 – Can’t Re-Declare a Variable within a Nested Block
May 26, 2014 3 Comments
A declaration space is a region of code within which you can’t declare two entities having the same name.
Defining a class creates a new declaration space, i.e. you can declare variables at the class level.
Defining a method creates a new declaration space, known as a local variable declaration space. A block of code within that method creates a nested local variable declaration space.
It’s of course an error to declare two variables of the same name within a local variable declaration space. It’s also an error to re-declare a variable of the same name in a nested local variable declaration space.
public void MethodA() { int y = 1; string y = "oops"; // ERROR int x = 12; Console.WriteLine(12); if (DateTime.Now.DayOfWeek == DayOfWeek.Thursday) { // ERROR: Can't re-declare x within nested local variable declaration space double x = 4.2; Console.WriteLine(x); } }