#1,103 – A Block Defines Both Scope and Declaration Space
May 23, 2014 2 Comments
- Scope is the region of code in which you can refer to a named entity using its unqualified name.
- Declaration space is a region of code within which you can’t declare two entities having the same name
A block of statements defines both a new scope and a new declaration space.
In the code below, the variable msg is declared within the block of statements following the if statement.
public class MyClass { public void AMethod() { if (DateTime.Now.DayOfWeek == DayOfWeek.Thursday) { // Can define variables within this block string msg = "Hi"; Console.WriteLine("{0}, it's Thursday. ", msg); } // ERROR: The name 'msg' does not exist in the current context Console.WriteLine(msg); } }
The block defines a new scope–the variable msg can be referred to by name anywhere within the block (after the declaration). This block also defines a declaration space–you can only declare one variable named msg within this block.
Pingback: Dew Drop – May 23, 2014 (#1783) | Morning Dew
Pingback: Dew Drop – May 27, 2014 (#1784) | Morning Dew