473,324 Members | 2,417 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

strange switch scoping

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?

public class MyClass
{
public static void Main()
{
int i=1;
switch (i)
{
case 1:
string n = "foo";
break;
case 2:
string n = "bar";
break;
}
}
}

Jan 13 '06 #1
3 1708
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
Jan 13 '06 #2
Michael Bray <mbray@makeDIntoDot_ctiusaDcom> wrote in
news:Xn***************************@207.46.248.16:
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'.


Ooopsie guys... I forgot to remove the 'return n' statements out of this
code... Code should be:

{
string n = "Mike";
n = n + n;
}
{
string n = "Joe";
n = n + n;
}

-mdb
Jan 13 '06 #3
Hi,

You can easily see where the scope of the local variables is. Just follow
the curly brackets - {}. Some of the operators allow blocks of only one
line. C# calls them embedded statements
Example:
you can write your *if* statement as

if(...)
a = 10;

or

if(...)
{
a =10;
}

In the first case a=10 is an embedded statement. Theoretically embeded
statement has to be a new scope for declarations, but it doesn't make sense,
thus C# correctly doesn't allow this and report an error.

Becasue of this you can safely trace declaration scopes via {}.

As you can see you don't have {} in your cases, so they share the switch
scope.

--

Stoitcho Goutsev (100)

<ap********@gmail.com> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.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?

public class MyClass
{
public static void Main()
{
int i=1;
switch (i)
{
case 1:
string n = "foo";
break;
case 2:
string n = "bar";
break;
}
}
}

Jan 13 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: David Stockwell | last post by:
Hi, Another of my crazy questions. I'm just in the process of learning so bear with me if you can. I actually ran it.... with two test cases TEST CASE 1: Say I have the following defined:...
5
by: Gunnar G | last post by:
Is there a problem with the declaration of the y-variable in the for loop? I'm not sure about the break, (if it should be there or not since I didn't write the original code), but the error:...
4
by: Joel Gordon | last post by:
Hi, When I try and compile the a class containing the following method : public void doSomething() { for (int i=0; i<5; i++) { IList list = new ArrayList(); Console.WriteLine( i /...
12
by: Andrew Ducker | last post by:
And no, this isn't a complaint about break - I'm very happy to make things explicit. However, why isn't the format something like: switch(myVariable) { case 1: { //Do Something
9
by: NevilleDNZ | last post by:
Can anyone explain why "begin B: 123" prints, but 456 doesn't? $ /usr/bin/python2.3 x1x2.py begin A: Pre B: 123 456 begin B: 123 Traceback (most recent call last): File "x1x2.py", line 13,...
3
by: morris.slutsky | last post by:
So every now and then I like to mess around with hobby projects - I often end up trying to write an OpenGL video game. My last attempt aborted due to the difficulty of automating game elements and...
17
by: Chad | last post by:
The following question stems from Static vs Dynamic scoping article in wikipedia. http://en.wikipedia.org/wiki/Scope_(programming)#Static_versus_dynamic_scoping Using this sites example, if I...
3
by: SPECTACULAR | last post by:
Hi all. I have a question here.. what kind of scoping does C++ use? and what kind does Smalltalk use? I know smalltalk is a little bit old .. but any help would be appreciated.
1
by: shaneal | last post by:
Hello all, I've been trying to learn some javascript and I ran into a strange scoping problem I was hoping someone here could help with. I have a fair amount of experience with functional...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.