January 1026

The trouble with Enums

Tags: | Categories: ASP.NET | Musings
E-mail | Permalink | Comments (0) | Post RSSRSS comment feed

Why are enums so hard to work with? For simple / trivial things, where you want to limit the options available to other developers an enum is a wonderful thing, such as a choice of colours or display modes. More often than not though I find that I need to Parse it in order to do something with it. For example I’m currently working on a project and (for whatever reason) we need to pass the AddressType through the QueryString and then use the value to filter my results. The code to do it looks something like this:

Dim addressType As IAddress.AddressType = CType([Enum].Parse(GetType(IAddress.AddressType), addressCodeParam), IAddress.AddressType)

I’m working in VB.NET at the moment, but in C# that would be

IAddress.AddressType addressType = (IAddress.AddressType)Enum.Parse(typeof(IAddress.AddressType), addressCodeParam);

It just isn’t clean, its hard to remember (which is one of the reasons for this post… so I can always find an example when I need it) and it’s not how I want to work with enums. To be honest I’m not sure how I’d do this differently, I spent too long yesterday looking at this to remember how I thought it should work, I can only see how it does work.

Maybe one day I’ll write a helper method to simplify how I interact with enums

Permalink | Comments (0)
Comments are closed