A Programmer's Dream

Parsing Enumerations

Posted by Stephen Wrighton on 08 Mar 2007

In my project at work, I deal with a large number of enumerations. Things such as the type of a key or the status of various objects. Now, I could have maintained a table in the database which corresponds to those enumerations, but that seems like double work to me, so when designing the database, I made the decision to just use VARCHAR fields where I would normally have the lookup identifier for the database table.

That means, I can just save my enum straight into the table rather than having to deal with looking up its corresponding value.

I also chose VARCHAR for a string representation in the database over an INT for just the numeric value behind the enum so that when looking at the actual data in the various tables, I could easily discern what those enums actually are.

Getting the string representation of an enum is something I've known how to do for quite a while, and do do it whenever I'm working with them and I need to see the chosen enum in the debug output. It's just a simple matter of using the ToString method of the enumeration.

Yet, I've never gone the other way, of taking a string back to the enum value. It's not a simple matter of using CType as enumerations are in actuality numbers and not the strings that I'm saving.

So, I went to my good friend Google.

And discovered this glob entry: Miscellaneous Debris: VB.Net and Enums

His issue was using the enumerations that are inherent parts of the VB.Net language, but the concept he described works regardless.

The solution is to basically, force the compiler to read the string, and compare the possible enum values to see which is the correct one using the parse command like thus:
[Enum].Parse(System.Type, Value)

So, for my purposes what I would use is:
[Enum].Parse(GetType(Status), dataReader("Status"))
And it works beautifully!

Tweet me @kidananubix if you like this post.

Tweet