Enum.TryParse in .NET 4.0

If you are using .NET 4.0, then Enum.TryParse<TEnum> is now provided out of the box and support flags enumeration. As given in the documentation, Enum.TryParse<> ‘Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. The return value indicates whether the conversion succeeded.

Here’s how to use it:

enum Result { Fail = 0, Pass = 1, Grace = 2 };

static void Main(string[] args)
string a = (Result.Pass || Result.Grace).ToString();
Result b;
bool success = Enum.TryParse<Result>(a, out b);
Console.WriteLine("{0} = {1}", success, b);



About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.


Ahmadreza said...

Nice post but I think a pipeline between Result.Pass Result.Grace is missed. Am I right?

Suprotim Agarwal said...

Thanks! yes the or symbol was missing..fixed it

Anonymous said...

its trick with Flags Attribute