Enums are Ints that Ain’t

Enumerations are incredibly useful in Microsoft .NET, but they can be odd to work with at times. While researching something to do with the new System.Addin namespace in C# 3.5, I was reminded of some enum craziness I’d forgotten.

Enumerations are implemented as collection of integer constants. You can cast any integer to an enum type, regardless of whether it’s been defined in the collection. That makes the code below legal, despite the fact that no item in our enum has a value of 55.

  1. public enum Color
  2. {
  3.     Black = 0,    
  4.     Red = 1,
  5.     Green = 2,
  6.     Blue = 3
  7. }
  8.  
  9. Brush.Color = (Color)55;

You can’t rely on the compiler to enforce legal enum values. This means if you’re using enums in case statements, you ought to include a default statement to catch those cases where an unexpected value gets passed. It’s always a good defensive coding measure, but I’d mistakenly assumed I could skip it in the case of enums. Not anymore.

[Edit: See this old post from Greg Vaughn for some other examples of Enum wackiness. Weird.]

Leave a Comment

Name: (Required)

E-mail: (Required)

Website:

Comment: