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:

[Flags]
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);
Console.ReadLine();
}

OUTPUT

image



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

3 comments:

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