Parsing Enums

I've been trying to apply generics in my code more often. A common place for change is any code that uses the gets a typename of any kind. For example, typeof(MyType) or MyObj.GetType().  Just created a nifty method to make parsing Enums a little easier.

Let's start with our Enum definition

public enum ShoeTypes {
    Nike,
    Sketcher,
    DrMartins
}

In the past, I have always been able to parse a string into an Enum using the Enum.Parse() method...

    ShoeTypes _myShoe = (ShoeTypes)Enum.Parse(typeof(ShoeTypes), "DrMartins"));

That's a bit wordy. So, I created a custom enum parser method using generics. My new version ends up looking like this...

ShoeTypes _myShoe = ParseEnum("DrMartins");

And code for ParseEnum looks like this...

    private T ParseEnum(string value)
    {
        return (T)Enum.Parse(typeof(T), value);
    }

Ideally, you would put this method in a utility class where it could be used throughout your code base. This is just a simple example how the use of generics can improve the organization and readability of your code.

Tags: