Scope

Scope and .net

There are often some basic misunderstandings about how scope works in .net

Simply put local variable scope is at conditional block and function level only; or to put it another way when writing a method/function/sub in C# or VB.Net you can have variables scoped by the method itself and control flow block like an if statement but not by something like a loop construct.

Consider the following simple application;

using System;
 
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Doing unscoped now");
        DoUnScopedMethod();
        Console.WriteLine("Doing scoped now");
        DoScopedMethod();
        Console.ReadKey();
    }
 
    private static void DoUnScopedMethod()
    {
        int unscoped;
        Random random = new Random();
 
        for (int i = 0; i < 10; i++)
        {
            unscoped = random.Next(10);
            Console.WriteLine((unscoped > i)? unscoped : -1);
        }
    }
 
    private static void DoScopedMethod()
    {
        Random random = new Random();
 
        for (int i = 0; i < 10; i++)
        {
            int scoped = random.Next(10);
            Console.WriteLine((scoped > i) ? scoped : -1);
        }
    }
}

In the both methods the IL generated will include the following section;

    .locals init (
        [0] class [mscorlib]System.Random random,
        [1] int32 i,
        [2] int32 scoped,
        [3] bool CS$4$0000)

With the only difference being the order of declaration (the 'unscoped' variable would be declared befiore random and i)1

However you don't need to go down to IL to see this in action simply try the following code:

    private static void DoScopedMethod()
    {
        Random random = new Random();
        for (int i = 0; i < 10; i++)
        {
            int scoped = random.Next(10);
            Console.WriteLine((scoped > i) ? scoped : -1);
        }
        int scoped = 5;
    }

note that the second declaration of scoped will show both a IDE red wiggly and a compile time error complaining that you are giving different meaning to another variable in a child scope.

MSDN has an old (but still relevant) article on this topic here: http://msdn.microsoft.com/en-us/library/ms973875.aspx

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License