This post originated from an RSS feed registered with .NET Buzz
by Jeff Key.
Original Post: Enums with duplicate values
Feed Title: Jeff Key
Feed URL: http://www.asp.net/err404.htm?aspxerrorpath=/jkey/Rss.aspx
Feed Description: Topics revolve around .NET and the Windows platform.
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:
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?