Search code examples
c#switch-statement

Why are variables that are declared in one case statement in scope for other cases?


Why does the following code compile? I would expect that it would complain about foo not being declared in the second case branch. Does the compiler handle the declaration such that it's in scope for all cases?

using System;

namespace Scratch
{
    class Scratch
    {
        public static void Main()
        {
            var x = 2;
            switch (x)
            {
                case 1:
                    var foo = "one";
                    Console.Out.WriteLine(foo);
                    break;
                case 2:
                    foo = "two"; // is foo in scope here?
                    Console.Out.WriteLine(foo);
                    break;
            }
        }
    }
}

Solution

  • What @JonSkeet said is correct: A "block" in the C/C++/C# sense is not the same thing as a "case" in the logical sense. But he didn't mention the "best practice" for fixing the issue: If you want to declare a variable inside one case of a switch statement, it's good practice to wrap the whole logical "case" in a block. This way the logical "case" and the actual "scope" recognized by the compiler will be one and the same.

    public static void Main()
    {
        var x = 2;
        switch (x)
        {
            case 1: {  // notice these braces I added
                var foo = "one";
                Console.Out.WriteLine(foo);
                break;
            }
            case 2:
                foo = "two"; // hooray! foo is no longer in scope here
                Console.Out.WriteLine(foo);
                break;
        }
    }