473,804 Members | 2,296 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Switch messed up or there is a reason for the madness?

Hi, i am new to C#. I am using some code similar to the one below. I am
declaring an ArrayList in one case block but the compiler complains
about it already being used in the previous case block. Is this normal
in C#? Assume that i follow this and in the first case block, i allocate
the memory using the "ArrayList mylist=new ArrayList()", and in the
second block, i just use the variable mylist like
"mylist.Add(som ething)". Now if the switch statement executes the second
case block first, that would case a violation, wouldn't it?

private void button1_Click(o bject sender, EventArgs e)
{
switch (button1.Text)
{
case "button1":
ArrayList mylist = new ArrayList();
mylist.Add(butt on1.Text);
button1.Text = "button2";
break;
case "button2":
ArrayList mylist = new ArrayList();
mylist.Add(butt on1.Text);
button1.Text = "button1";
break;
default:
break;
}
}
BRAMOIN

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #1
10 1271
Hi, can you post the exact error you get out of the compiler, please?

Thanks!

-- Tom

Meya-awe wrote:
Hi, i am new to C#. I am using some code similar to the one below. I am
declaring an ArrayList in one case block but the compiler complains
about it already being used in the previous case block. Is this normal
in C#? Assume that i follow this and in the first case block, i allocate
the memory using the "ArrayList mylist=new ArrayList()", and in the
second block, i just use the variable mylist like
"mylist.Add(som ething)". Now if the switch statement executes the second
case block first, that would case a violation, wouldn't it?

private void button1_Click(o bject sender, EventArgs e)
{
switch (button1.Text)
{
case "button1":
ArrayList mylist = new ArrayList();
mylist.Add(butt on1.Text);
button1.Text = "button2";
break;
case "button2":
ArrayList mylist = new ArrayList();
mylist.Add(butt on1.Text);
button1.Text = "button1";
break;
default:
break;
}
}
BRAMOIN

*** Sent via Developersdex http://www.developersdex.com ***

Nov 17 '05 #2
Meya-awe <br*****@yahoo. com> wrote:
Hi, i am new to C#. I am using some code similar to the one below. I am
declaring an ArrayList in one case block but the compiler complains
about it already being used in the previous case block. Is this normal
in C#? Assume that i follow this and in the first case block, i allocate
the memory using the "ArrayList mylist=new ArrayList()", and in the
second block, i just use the variable mylist like
"mylist.Add(som ething)". Now if the switch statement executes the second
case block first, that would case a violation, wouldn't it?


It's irritating, but the scope of a variable declared in a switch block
is the *whole* switch block, not just the case you're in. However, if
you put braces round your case blocks, it should be okay.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #3
> private void button1_Click(o bject sender, EventArgs e)
{
switch (button1.Text)
{
case "button1":
ArrayList mylist = new ArrayList();
mylist.Add(butt on1.Text);
button1.Text = "button2";
break;
case "button2":
ArrayList mylist = new ArrayList();
mylist.Add(butt on1.Text);
button1.Text = "button1";
break;

As Jon Skeet said you could use {} inside the case blocks.

case 1:
{
ArrayList mylist = new ArrayList();
break;
}
case 2:
{
ArrayList mylist = new ArrayList();
break;
}

The other possibility is to accept that a declaration lasts over the
whole switch statement and only declare the ArrayList in the first
case.

case "button1":
ArrayList mylist = new ArrayList();
break;
case "button2":
mylist = new ArrayList();
break;

While not very logical, it does work just fine.

--
Marcus Andrén
Nov 17 '05 #4
Thanks for everyone's response on this. The first part of my questions
is how to get around this. And Jon already pointed this out. I will use
the braces. The second part of my question is why was this changed in C#
to treat the variable's scope global to the entire switch statement.

BRAMOIN

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #5
Tom,
Here is the exact error message, may be this was requested for
historical reason? Please let me know if i was confusing in my
statements or what?

Error 2 A local variable named 'mylist' is already defined in this
scope C:\visual studio
2005\Projects\T estingSwitchVar iableScope\Test ingSwitchVariab leScope\Form
1.cs 29 31 TestingSwitchVa riableScope
thx,
BRAMOIN

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #6
What is the purpose of this code? It doesn't seem useful to declare a
variable inside a switch statement unless its use has side effects.

Nov 17 '05 #7
Mark Wilden <mw*****@broadl ine.tv> wrote:
What is the purpose of this code? It doesn't seem useful to declare a
variable inside a switch statement unless its use has side effects.


I always declare variables as close as I can to first use, and in the
tightest scope possible. Sure, the ArrayLists in this example aren't
being used, but it's reasonable to assume that in the real world, the
variable is actually useful.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #8
Yes, Jon is correct, it is best to declare the variables as close as
first use. The practical application is when you have a routine where
it handles a specific set of sequences or cases (for example, a handler
which plots the next course for an airplane, gets notified every second
that it has to compute a new direction for an airplane, once it gets
notified, it 500msecs before the data becomes available for it to
compute a trajectory, the trajectory and all data needs to be saved
everytime a course is plotted [i.e. a new block of memory is required to
plot the next course]). In one of the cases, you always want to setup
memory so in the subsequent cases you would not have to do this and can
do computation. Hope this makes sense.

BRAMOIN

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #9
I agree about declaring variables close to their use. I was, however,
commenting on the specific code that was posted.

In general, I would say that declaring a variable inside a switch
statement constitutes a "code smell," and that the code should probably
be factored into a function of its own.

Which is not to say I've never done it, and used the block trick, which
is also necessary in C and C++, not just in C# (in reply to another
poster).

Nov 17 '05 #10

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

Similar topics

5
3340
by: Martin Lucas-Smith | last post by:
Is there any need to keep the final break in a switch which uses a default at the end? I.e: switch ($data) { case 'foo': # Action break;
15
7606
by: Mike and Jo | last post by:
I've been converting some code to C++. I'm trying to use the Switch function to compare a result. Is it possible to use switch to evaluate '>0', '<0', 0? Example switch (result) { case (>0): case (<0):
18
3465
by: Minti | last post by:
I was reading some text and I came across the following snippet switch('5') { int x = 123; case '5': printf("The value of x %d\n", x); break; }
6
449
by: Mark Broadbent | last post by:
How on earth did Anders & co arrive at this awful switch/ case/ select statement? Not only does it lose the abilty to do an intelligent switch a-la VB eg. using >, <, list of values etc .... but it also lacks a "C# feel" e.g. I would have expected a brace pair to be required between each case label .... and the break to prevent fall thru is pointless? Am I misguided in thinking that Anders has tried to adhere to the C++ case
10
12328
by: Evie | last post by:
I understand that when a switch statement is used without breaks, the code continues executing even after a matching case is found. Why, though, are subsequent cases not evaluated? I wrote a program to demonstrate how a switch without breaks behaves vs. how I expected it to behave. The code includes: (1) a switch statement with breaks (2) the if/else statements that have the same results as (1) (3) a switch statement without breaks...
9
1611
by: Raj | last post by:
public static void HandleException(ref Exception io_exException, bool i_blnPropagateException) { switch (true) { case io_exException is ApplicationHandledException: { if (i_blnPropagateException) {
11
4105
by: raylopez99 | last post by:
Keep in mind this is my first compiled SQL program Stored Procedure (SP), copied from a book by Frasier Visual C++.NET in Visual Studio 2005 (Chap12). So far, so theory, except for one bug (feature?) below. At some point I'm sure I'll be able to laugh about this, akin to forgeting a semi-colon in C/C++, but right now it's frustrating (time to sleep on it for a while). Problem-- For some reason I get the error when trying to save files...
1
2524
by: Kayvine | last post by:
Hi guys, this is a question I have for an assignment, it is pretty long, but I am not asking for the code(well if someone wants to write I'll be really happy, lol), but I just want to know how to start it and what main topics in C I will need to cover in the assignment. Thanks a lot. CSC180 Assignment #3: Menu Madness Due Date: Thursday, November 8th at 1:00am Contents: · General Info · What to Hand In o Submission Instructions
6
1481
by: BigT | last post by:
I have 3 questions to the code below which is pretty messed up (newby). the program should pull a random number between 1-6 when i push a button and show it on an LCD (button and LCD are set up) 1. how do i include the switch correctly 2. how do i set up a random number counter 3. how do read the number when i push the button and link the random no. to the LCD equivalent. Any help appreciated.
0
9714
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
10347
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10090
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9173
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7635
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5531
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4308
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.