#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); } }
Pingback: Dew Drop – May 27, 2014 (#1784) | Morning Dew
Good job, “declaration space”, “nested declaration space”. Thank you for the knowledge Sean.
Sorry, it’s “local declaration space” and “nested local declaration space”.
We can hide a class declaration space variable with a local declaration space variable, but we can’t hide a local declaration space variable with a nested local declaration space variable.