Jeff Key

It works on my machine

Sponsors

My Job

My stuff

Old stuff

Useful Stuff

Enums with duplicate values

Enums and switch statements go hand-in-hand. What do you do when you you have two enum values that have the same value? Nothing elegant, I'm sure, since a switch with two values that resolve to the same backing value generate a “The label 'case <value>:' already occurs in this switch statement“ error. Consider the MessageBoxIcon enum:

public enum MessageBoxIcon
{
  Asterisk = 64;
  Error = 16;
  Exclamation = 48;
  Hand = 16;
  Information = 64;
  None = 0;
  Question = 32;
  Stop = 16;
  Warning = 48;
}

Creating a switch statement for this enum results in compiler errors because some underlying values are duplicates. The only way to deal with this, that I'm aware of, is to use a single enum for each underlying value, ie. Error would represent Hand and Stop, too.  The resulting code is not just unreadable, it's misleading. The developer must use comments to express their intent, and that's unacceptable.

Since C# doesn't support fall-through with code bodies, why not allow fall-through if the values are the same? For example:

switch (icon)
{
 case MessageBoxIcon.Error:
 case MessageBoxIcon.Hand:
 case MessageBoxIcon.Stop:
  // something;
  break;
}

The compiler can recognize that the backing values are the same and compile to:

switch (icon)
{
  case 16:
  // something;
  break;
}

Is that reasonable? Am I missing something else altogether?

Comments

Chris Nahr said:

I agree, disallowing duplicate case values looks like a C holdover that never had a good reason in the first place.

Duplicate values on different case statements are clearly an error but what possible reason is there to disallow duplicate values on the same statement, enum or not?

I can't think of any. The compiler could simply fold them; maybe optionally emit a warning at the highest level.
# May 9, 2004 4:31 AM