Enum: the ‘simple’ C# value type we love to complicate

Enums are simple collections of constant values, using an underlying integer to store the value.  Enums implement IComparable, IFormattable and IConvertible while still being value types and give us everything we need to store and use things like status values, action codes, colours etc…

You can use enum values in both server and client code, but when the user interface displays an enum, or when the user must be able to choose enums from a combobox, we can run into complications with enums. Making enum display values more human readable and showing values in a particular order are not that easy to implement. In this article, I will show you a solution used in a WPF client consuming WCF web services.

Lets say we want to create a web service for a laundry process. To track the status of a piece of clothing, we create an enum in the data contract:

1: public enum LaundryStatus 2: { 3: [EnumMember] 4: InHamper= 0, 5: [EnumMember] 6: InLaundryBatch = 1, 7: [EnumMember] 8: WashingInProgress = 2, 9: [EnumMember] 10: WaitingForDryer = 3, 11: [EnumMember] 12: DryingInProgress = 4, 13: [EnumMember] 14: Dried = 5 15: }

Raw Enum strings in a combobox

Raw Enum strings in a combobox

Simple, right? We have 6 statuses which we can now use in both server and client code.  We have to decorate the class with DataContractAttribute and each enum value with an EnumMemberAttribute to have WCF serialize and de-serialize them properly, but the code declaring the laundry statuses still looks pretty simple. We can write code that is easily understood and easy to maintain:

1: switch (item.Status) 2: { 3: case InHamper: 4: case Dried: 5: beingProcessed = false; 6: break; 7: case InLaundryBatch: 8: case WashingInProgress: 9: case WaitingForDryer: 10: beingProcessed = true; 11: break; 12: }

Improving readability

The first improvement you will want to make, is to have proper display strings. People like spaces, commas an capitals in proper places when they look at a user interface; users will want to see “Drying is in progress” rather than “DryingInProgress”. How do we accomplish that ? We can use the EnumMemberAttribute’s Value property to declare a human friendly string:

Page 1 of 7 | Next page