JCooney.NET

Joseph Cooney's Weblog

My Links

Blog Stats

News

I work for:


see also:
Dominic Cooney
Patrick Cooney

Archives

Image Galleries

My GotDotNet Samples

Comfortably Enum

Fellow .NET junkie A Henry P. Erich III posted an entry on parsing enums. Scott Galloway noted in the comments that Henry should probably check out Enum.IsDefined. I'd like to second that. The way it currently stands Henry's code could return enum values that don't exist in the list of current enum values. For example if you've defined an enumeration Food with the values Sausage = 1, Eggs = 2, Cheese = 3 and Herrings = 4 it could return a value outside that range.

How is this possible? Aren't enums a list of predefined values, that can only be one of those values? Well.....no. In the code below we create an enum called TestEnum with the values Foo = 1, Bar = 2 and Undefined = 3. We use a modified version of Henry's code and pass it values “Foo“, “Bar“, “ThisWontWork“ and “99“. The first 3 work as you would expect - foo and bar are parsed without incident. “ThisWontWork“ throws an exception which is caught and returns a “default“ value of TestEnum.Undefined. The last one returns a brand new TestEnum value with an underlying numeric value of 99. It is not in our existing list of enums. After I saw this I made sure all my methods were checking IsDefined for any enum arguemnts they receive, and all my switch statements that use an enum as an argument have a default case that throws an exception of some sort.

1using System;
2
3namespace ComfortablyEnum
4{
5 class EnumTest
6 {
7  public enum TestEnum
8  {
9   Foo = 1,
10   Bar = 2,
11   Undefined = 3
12  }
13
14  [STAThread]
15  static void Main(string[] args)
16  {
17   TestEnum parsedItem = ParseEnum("Foo");
18   PerformSomeActionOnEnumValue(parsedItem);
19
20   parsedItem = ParseEnum("Bar");
21   PerformSomeActionOnEnumValue(parsedItem);
22
23   parsedItem = ParseEnum("ThisWontWork");
24   PerformSomeActionOnEnumValue(parsedItem);
25
26   parsedItem = ParseEnum("99"); // what about this?

27   PerformSomeActionOnEnumValue(parsedItem);
28
29  }
30
31  static TestEnum ParseEnum(string itemToParse)
32  {
33   TestEnum returnValue;
34   try
35   {
36    // Validate the enum with a try/catch

37    returnValue = (TestEnum)Enum.Parse(typeof(TestEnum), itemToParse, true);
38   }
39
40   catch
41   {
42    // Set to default or whatever other handling you want.

43    returnValue = TestEnum.Undefined;
44   }
45   return returnValue;
46  }
47
48  static void PerformSomeActionOnEnumValue(TestEnum argument)
49  {
50   switch (argument)
51   {
52    case TestEnum.Foo:
53     Console.WriteLine("Take some action on foo enum value...");
54     break;
55
56    case TestEnum.Bar:
57     Console.WriteLine("Take some action on bar enum value...");
58     break;
59
60    case TestEnum.Undefined:
61     Console.WriteLine("Take some action based on Undefined enum value...");
62     break;
63
64    default:
65     Console.WriteLine("How is this possible....there are only 3 values for this enum?");
66     break;
67   }
68  }
69 }
70}
71

posted on Wednesday, April 07, 2004 4:15 PM

Feedback

# re: Comfortably Enum 4/8/2004 12:44 AM Henry Erich III

And here is a MS article, the info we are talking about is down at the bottom.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconvaluetypeusageguidelines.asp

Also, how do you get your code to display so neatly?

# re: Comfortably Enum 4/8/2004 12:52 AM JosephCooney

Hi Henry - that is a good link. Here is the utility I used to format that code.

http://www.squishyweb.com/ware/products.asp?q=squishysyntax

# re: Comfortably Enum 4/8/2004 1:22 AM Henry Erich III

Thanks Joseph! Have a fun day!

# re: Comfortably Enum 4/8/2004 7:40 PM Scott Galloway

One slight issue with Enum.IsDefined whjen compared with Enum.Parse is that the latter allows for case insensitivity whilst the former does not. Normally this isn't a problem (I have tended to stich to a single case for Enum items - usually upper case). One nice way round this is to use Title case only (so first letter upper, rest lower). You can then use System.Globalization.TextInfo.ToTitleCase() to convert your input string to the correct case (http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemGlobalizationTextInfoClassToTitleCaseTopic.asp?frame=true)

# re: Comfortably Enum 4/13/2004 10:41 AM secretGeek

Great title! (i.e. 'Comfortably Enum')
love it!

# re: Enums and validation 5/10/2004 4:08 PM Eric Gunnerson's C# Compendium

#  9/11/2004 6:30 AM

Title  
Name  
Url
Security Word (prevent comment spam)
Protected by FormShield
Comments