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.
They can be in any order you want. And no, it's not always bad to use actual numbers. But not magic numbers. Use numbers if you are comparing an int
, like maybe
switch (numberOfItems)
{
case 0:
break;
case 1:
break;
default:
break;
}
(Of course, this is only an example and I can't imagine seeing this code in the real world)
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.
They don't have to be consecutive. Although I do that just for clarity's sake.
Order does not matter, the compiler will do that work for you.
I prefer to use either an enumeration or a const int to provide meaning to the number, particularly when it is being maintained by somebody else down the road.
It's possible to do both. The syntax is this: (you're close)
switch(someInt)
{
case 1:
// some code
break;
case 2:
// some code
break;
case 3:
// some code
break;
default:
// code for "else" case
break;
}
or is it possible to do something like the following:
switch(someInt)
{
case 1:
case 3:
case 5:
// some code
break;
}
Note the colons and break
s.
As for the use of magic numbers, in general, I prefer to put literals in constants, but I make exceptions for glaringly obvious numbers such as the lowest number to check for factor divisibility is 2.
As a small optimization, you can order your case values based on actual/expected frequency. I'd also add a "default" case so you'll be able to easily discover where you've used your enum and forgotten to account for it. This is another reason to use enum values over constants.
精彩评论