Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#4.0

A Generic enum Parser in C#

5.00/5 (7 votes)
30 May 2011CPOL 17.4K  
A possibly simpler version of this is to create an extension method for strings:public static class MyExtensions{ public static TEnum ParseEnum(this string value, bool ignoreCase = false) where TEnum : struct { TEnum tenumResult; ...
A possibly simpler version of this is to create an extension method for strings:
C#
public static class MyExtensions
{
    public static TEnum ParseEnum<TEnum>(this string value,
        bool ignoreCase = false) where TEnum : struct
    {
        TEnum tenumResult;
        Enum.TryParse<TEnum>(value, ignoreCase, out tenumResult);
        return tenumResult;
    }
}

Note that you also do not need to assign or return default(TEnum) because Enum.TryParse will always set tenumResult for you, regardless of success or failure when parsing.

Usage:
C#
var enumValue = "One".ParseEnum<EnumOne>();

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)