473,387 Members | 1,348 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,387 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 1709
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: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.