Strongly Typed Enumeration Retrieval Using Generics

Here is a small code snippet to retrieve a strongly typed value from an enum in C#. This would come in handy if you need to instantiate class values based on an enum value as this method provides both strong typing, and correct casting based on the generic type you need.

public static T ParseEnum<T>(string value) where T : struct
{
    try
    {
        return (T)Enum.Parse(typeof(T), value, true);
    }
    catch (ArgumentException) { throw; } // bad form, shortened for brevity
}

Calling code would be like the following:

Utilities.ParseEnum<TypeExpected>(ValueToRetrieve);

This should take care of any messy casting for enums, and reduces code smell. Of course enums are messy in and of themselves, but they are a necessary evil, and hopefully this utility method will make using them a little easier.

No comments yet