jQuery and ASP.NET

June 2, 2010

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



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

3 Responses to "Enum.TryParse in .NET 4.0"
  1. Ahmadreza said...
    June 7, 2010 6:20 AM

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

  2. Suprotim Agarwal said...
    June 7, 2010 7:15 AM

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

  3. Anonymous said...
    June 7, 2010 3:23 PM

    its trick with Flags Attribute

 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions