Click here to Skip to main content
11,630,144 members (79,710 online)
Click here to Skip to main content

Tagged as

A Generic enum Parser in C#

, 7 Jun 2011 CPOL 4.3K 1
Rate this:
Please Sign up or sign in to vote.
The ParseEnum method will not work where we use a version below .NET Framework 4.0 because of the TryParse method. So those who need to use it in below .NET Framework 4.0 or in .NET Framework 4.0, the following extension methods will be helpful:public static TEnum ParseEnum(this...
The ParseEnum method will not work where we use a version below .NET Framework 4.0 because of the TryParse method. So those who need to use it in below .NET Framework 4.0 or in .NET Framework 4.0, the following extension methods will be helpful:

public static TEnum ParseEnum<TEnum>(this string dataToMatch, bool ignorecase = default(bool))
  where TEnum : struct
{
  return dataToMatch.IsItemInEnum<TEnum>()() ? default(TEnum) : 
     (TEnum)Enum.Parse(typeof(TEnum), dataToMatch, ignorecase );
}
 
public static Func<bool> IsItemInEnum<TEnum>(this string dataToCheck)
   where TEnum : struct
{
   return () => { return string.IsNullOrEmpty(dataToCheck) || !Enum.IsDefined(typeof(TEnum), dataToCheck); };
}
Usage:
object[] items = new object[] { "One".ParseEnum<EnumTwo>(), "Two".ParseEnum<EnumTwo>() };
Note that these extension methods are part of .NET Extensions Methods Library for C# and VB.NET[^] project in the CodePlex.

License

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

Share

About the Author


You may also be interested in...

Comments and Discussions

 
GeneralRe: Seems it's available from .Net 3.5 (http://msdn.microsoft.co... Pin
Espen Harlinn30-May-11 11:02
mvpEspen Harlinn30-May-11 11:02 
GeneralThanks Kiswa00. Pin
Mohammad A Rahman7-Jun-11 11:21
memberMohammad A Rahman7-Jun-11 11:21 
GeneralReason for my vote of 3 See comment on alternate. Pin
kiswa007-Jun-11 2:25
memberkiswa007-Jun-11 2:25 
GeneralTwo things: One, I think you mean "a version below .NET Fram... Pin
kiswa007-Jun-11 1:58
memberkiswa007-Jun-11 1:58 
GeneralTryParse is available from at least 2.0 and up. Pin
John Simmons / outlaw programmer30-May-11 2:10
mvpJohn Simmons / outlaw programmer30-May-11 2:10 
GeneralRe: Sorry it is my mistake, I should mentioned it clearly before... Pin
Mohammad A Rahman30-May-11 2:36
memberMohammad A Rahman30-May-11 2:36 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150723.1 | Last Updated 7 Jun 2011
Article Copyright 2011 by Mohammad A Rahman
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid