Traditional switch blocks have one scope, so the following throws a compiler error "A local variable or function named 'message' is already defined in this scope":

switch(value)
{
    case 1:
        string message = "Val: 1";
        break;
    case 2:

        string message = "Val: 2";
        break;
}

As Eric Lippert states:

A reasonable question is "why is this not legal?" A reasonable answer is "well, why should it be"? You can have it one of two ways. Either this is legal:

switch(y)
{
    case 1:  int x = 123; ... break;
    case 2:  int x = 456; ... break;
}

or this is legal:

switch(y)
{
    case 1:  int x = 123; ... break;
    case 2:  x = 456; ... break;
}

but you can't have it both ways. The designers of C# chose the second way as seeming to be the more natural way to do it.

There are other good explanations too, like this one:

I think a good reason is that in every other case, the scope of a “normal” local variable is a block delimited by braces ({}).

So then why does scoping behave differently with a type pattern matching switch block?

Animal p = new Dog();

switch(p)
{
    case Dog a:
        break;
    case Cat a: // Why is this legal?           
        break;
}

Related posts

Recent Viewed