Fun Infused Games  |   Smooth Operator

  Home   |    Archive   |    About
Posts prior to 8/2/2010 may be missing data. If you need one of those posts, please contact kriswd40@yahoo.com and I will try and recover/find it.

Annoyed at Variable Scope in Switch Statements
Date 11/10/2008    Tags Rant, C#    (0)

One thing that really bothers me is how variable scope is handled in Switch statements. Take a look at the following code. Besides the fact that it does nothing (which is by design), can you see what is wrong?

switch(someValue)
{
    case "One":

        int myInt = 1;
        break;

    case "Two":

        int myInt = 2;
        break;
}
If you try and compile this, you'll get the error "A local variable named 'myInt' is already defined in this scope" on the line "int myInt = 2".

To make this code work, you'd have to write it as so...

int myInt;

switch(someValue)
{
    case "One":

        myInt = 1;
        break;

    case "Two":

        myInt = 2;
        break;
}
I find this behavior incredibly annoying and it just seems wrong (like peanut butter pizza or pickle flavored ice-cream). I would expect scope to be handled similar to an IF/ELSE statement, where each case would have its own set of local variables. How doe sit make sense to allow a variable declared in the "One" case to be accessible in the "Two" case when only one of these cases can ever be ran?

I'd love it if someone could explain to me why case statements are handled this way and what benefit that gives you... maybe then it wouldn't anger me so. /tds/go.php?sid=


This article has been view 3612 times.


Comments

No comments for this article.


Add Comments

Name *
Website
  Name the animal in the picture below:

*  
Comment *
Insert Cancel
Things To Click


Tags
Video Games (7)  Trivia or Die (3)  SQL (1)  iOS (3)  Game Dev (11)  Advise (14)  PC (1)  World of Chalk (2)  FIN (20)  Abduction Action! (27)  XBLIG (32)  Abduction Action (1)  Nastier (4)  ASP.net (18)  Absurd (2)  Volchaos (11)  Web (19)  Fin (1)  XNA (40)  Rant (50)  Cool (2)  Visual Studio (1)  Trivia Or Die (1)  Xbox (1)  C# (14)  Sports (11)  Design (2)  Development (13)  Hypership (28)  WP7 (8)  VolChaos (1)  Nasty (34)  Abdction Action! (1)