Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
            }
        }
    }
}
like image 864
Cody Avatar asked Sep 13 '12 23:09

Cody


1 Answers

Why does the following code compile?

Because the language is designed in a brain-dead way in this particular area :(

The scope of a local variable is the block in which it's declared, and it's accessible at any point lexically after the declaration.

No, I wouldn't design the language that way either. I'm not a fan of the design of switch in C#...

like image 115
Jon Skeet Avatar answered Nov 14 '22 22:11

Jon Skeet