Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET C# switch statement string compare versus enum compare

Tags:

performance

c#

I'm interested in both style and performance considerations. My choice is to do either of the following ( sorry for the poor formatting but the interface for this site is not WYSIWYG ):

One:

string value = "ALPHA";

switch ( value.ToUpper() )
{
   case "ALPHA":
     // do somthing
     break;
   case "BETA":
     // do something else
     break;
   default:
     break;
}

Two:

public enum GreekLetters
{
    UNKNOWN= 0,
    ALPHA= 1,
    BETA = 2,
    etc...

}

string value = "Alpha";
GreekLetters letter = (GreekLetters)Enum.Parse( typeof( GreekLetters ), value.ToUpper() );

switch( letter )
{
   case GreekLetters.ALPHA:
      // do something
      break;
   case GreekLetters.BETA:
      // do something else
      break;
   default:
      break;
}

Personally, I prefer option TWO below, but I don't have any real reason other than basic style reasons. However, I'm not even sure there really is a style reason. Thanks for your input.

like image 252
Dan7el Avatar asked Dec 22 '09 16:12

Dan7el


3 Answers

The second option is marginally faster, as the first option may require a full string comparison. The difference will be too small to measure in most circumstances, though.

The real advantage of the second option is that you've made it explicit that the valid values for value fall into a narrow range. In fact, it will throw an exception at Enum.Parse if the string value isn't in the expected range, which is often exactly what you want.

like image 198
JSBձոգչ Avatar answered Oct 17 '22 18:10

JSBձոգչ


Option #1 is faster because if you look at the code for Enum.Parse, you'll see that it goes through each item one by one, looking for a match. In addition, there is less code to maintain and keep consistent.

One word of caution is that you shouldn't use ToUpper, but rather ToUpperInvariant() because of Turkey Test issues.

If you insist on Option #2, at least use the overload that allows you to specify to ignore case. This will be faster than converting to uppercase yourself. In addition, be advised that the Framework Design Guidelines encourage that all enum values be PascalCase instead of SCREAMING_CAPS.

like image 31
Jeff Moser Avatar answered Oct 17 '22 18:10

Jeff Moser


I can't comment on the performance part of the question but as for style I prefer option #2. Whenever I have a known set of values and the set is reasonably small (less than a couple of dozen or so) I prefer to use an enum. I find an enum is a lot easier to work with than a collection of string values and anyone looking at the code can quickly see what the set of allowed values is.

like image 28
TLiebe Avatar answered Oct 17 '22 18:10

TLiebe