Click here to Skip to main content
15,887,683 members
Articles / Programming Languages / C# 4.0
Alternative
Tip/Trick

A Generic enum Parser in C#

Rate me:
Please Sign up or sign in to vote.
5.00/5 (7 votes)
30 May 2011CPOL 16.3K   5   6
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)


Written By
Software Developer (Senior) Undead Labs
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralReason for my vote of 5 This is exactly what I was looking f... Pin
hillel817-Jun-11 6:56
hillel817-Jun-11 6:56 
GeneralReason for my vote of 5 good Pin
SachinS930-May-11 22:26
SachinS930-May-11 22:26 
GeneralReason for my vote of 5 Nice.. Pin
Pritesh Aryan21-May-11 1:04
Pritesh Aryan21-May-11 1:04 
Generalgood solution..... Btw, ...it's working well though if it is... Pin
Pritesh Aryan20-May-11 3:37
Pritesh Aryan20-May-11 3:37 
Generalthis extension method will access using string? like string... Pin
Pritesh Aryan20-May-11 2:55
Pritesh Aryan20-May-11 2:55 
GeneralRe: The way extension methods are declared using the "this" keyw... Pin
Ian Good21-May-11 19:30
Ian Good21-May-11 19:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.