Fun Infused Games  |   Smooth Operator RSS 

  Home   |    Archive   |    Subscribe   |    Search   |    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


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