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;
}
}
}
}
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#...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With