Search code examples
c#switch-statementmagic-numbers

c# switch statement question


I'll cut to the chase. I have two questions about switch that are simple, but I can't figure them out.

First:

in c# switch statements, do case statements have to be consecutive (with ints)?

For example:

switch(someInt)
{
    case 1
    // some code
    case 2
    // some code 
    case 3 
    // some code
}

or is it possible to do something like the following:

switch(someInt)
{
    case 1 
    case 3
    case 5
}

I know that normally if-else statements are used for something like that, but I'm just curious to know if its possible.

Also, is it considered magic numbers to use actual numbers in case statements? Or is is better practice to declare constants for use in the case statements?

Thanks!

Edit:

Thanks to all of you for your responses! I appreciate it.


Solution

  • The values of the case statements definitely do not need to be consecutive.

    You also aren't tied to only using integer values. Strings work just as well.

    If you're worried about magic numbers, your best bet is to create an enumeration. It will convey the meaning of those magic numbers. Otherwise, have at it and enjoy.