Declaring a Variable within a Block of Statements

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:
1
2
3
4
5
6
7
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.


1
2
3
4
5
6
7
if (<span class="skimlinks-unlinked">DateTime.Now.DayOfWeek</span> == DayOfWeek.Wednesday)
{
    string bestFood = "Pizza";
    Console.WriteLine(bestFood);
}
 
// Can't access bestFood variable out here