#964 – Declaring a Variable within a Block of Statements
October 31, 2013 Leave a comment
When you declare a block of statements in your code, you can declare variables within that block that will have a scope that is local to the block. This is, the variable will be visible only to other code within the block.
This is most often done within a function:
static void DoSomething() { // Variable local to this function string name = "Bob"; Console.WriteLine(name); }
You can, however, declare local variables within any block of statements.
if (DateTime.Now.DayOfWeek == DayOfWeek.Wednesday) { string bestFood = "Pizza"; Console.WriteLine(bestFood); } // Can't access bestFood variable out here