I recently stumbled across a blog post demonstrating how to convert enums to strings using the Description attribute. I thought it might be useful to expand on that example by providing a function that reverses the process (e.g. takes in the resulting string and converts it back to the enum). This would allow you to do things like store off the description into a database and load it back into an enum or populate a dropdown list with the descriptions and save the user's selection back into your domain as an enum.
Rather than diving straight into code, let's just take a quick look at what the finished product lets you do. Say you have the following enumeration:
The code from the original blog post will allow you to retrieve any of the Description attributes by calling the ToDescription extension method:
And with the code I wrote, you will be able to perform the opposite conversion by calling the ToEnum extension method:
Ok, now let's look at how it all works:
Here is the slightly modified version of the extension method from the original blog post. It's pretty straightforward. It's an extension method on the Enum class that uses reflection to grab the Description attribute and output it. If no Description attribute is found, it returns the result of the ToString() function:
And here is my extension method that reverses the process. This extension method on the string class iterates over all enum values for the given enumeration, trying to find the one that has a Description attribute that matches the string that called it. If the extension method can't find this enum, it returns the default enum passed in the parameters.
I'm sure there are probably cleaner ways of doing this, but for mypurposes this works great and is easy to implement and manage. I'd be interested in hearing how others are handling this scenario in their own apps and whether this implementation would be useful at all. Let me know in the comments!