ap********@gmail.com wrote in news:1137168111.299665.269300
@z14g2000cwz.googlegroups.com:
The following code snippet fails to compile with "a local variable
named n is already defined in this scope." This makes me
uncomfortable, but I could not tell you exactly why. My instincts are
telling me that each case should be a seperate block, I guess. Any
comments?
Your instinct is a common one, but unfortunately, wrong. Variables in a
switch block are common to the switch block.
However, if you really want to use the same variable name as you have
shown, you can use a little trick. Just surround each of the switch
case code blocks with {...}, like this:
int i = 0;
switch (i)
{
case 1:
{
string n = string.Empty;
break;
}
case 2:
{
string n = string.Empty;
break;
}
}
Incidentally, this isn't specific to switch/case. You can use it right
in the middle of code:
public string GetName()
{
{
string n = "Mike";
n = n + n;
return n;
}
{
string n = "Joe";
n = n + n;
return n;
}
}
It isn't exactly pretty, but it works - at least from a compiler
perspective.
The really *wierd* thing about this, and maybe some of the C#/Compiler
gurus can address, is that the variable *DOESN'T* go out of scope. In
other words, if I debug the GetName() function shown above, when I get
to the line:
string n = "Joe";
the debugger says that 'n' has a value of 'MikeMike'.
WHY??? It seems that the compiler is honoring the {...} but the
runtime is not. Is this a compiler bug? Is it a CLR bug?? I'm not
sure.
It's for this reason that I mark this post with the disclaimer, USE AT
YOUR OWN RISK. I, Michael Bray, will not be responsible for any rockets
which fly off course as a result of this "bug". :)
-mdb