The Artima Developer Community
Sponsored Link

.NET Buzz Forum
Enums with duplicate values

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Jeff Key

Posts: 481
Nickname: jeffreykey
Registered: Nov, 2003

Jeff Key is legally sane, but questionably competent.
Enums with duplicate values Posted: May 8, 2004 5:23 PM
Reply to this message Reply

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.
Latest .NET Buzz Posts
Latest .NET Buzz Posts by Jeff Key
Latest Posts From Jeff Key

Advertisement

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?

Read: Enums with duplicate values

Topic: 70 New Developer Resourcs on .NET Compact Framework! Previous Topic   Next Topic Topic: Das lizenzkostenfreie Axinom Enterprise Content Management System basierend auf .NET

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use