Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic version of Enum.Parse in C#

Tags:

c#

enums

generics

I have regularly wondered why C# has not yet implemeted a Generic Enum.Parse

Lets say I have

enum MyEnum {    Value1,    Value2 } 

And from an XML file/DB entry I wish to to create an Enum.

MyEnum val = (MyEnum)Enum.Parse(typeof(MyEnum), "value1", true); 

Could it not have been implemented as something like

MyEnum cal = Enum.Parse<MyEnum>("value1"); 

This might seem like a small issue, but it seems like an overlooked one.

Any thoughts?

like image 252
Adriaan Stander Avatar asked Feb 11 '10 19:02

Adriaan Stander


People also ask

What does enum Parse do?

Parse(Type, String) Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

How to Parse string into enum?

Parse() method parse the specified string to enum member. However, it throws an exception if the specified string does not match with any enum member name. In the above example, the Enum. Parse() method converts the string value day1 to enumeration type and returns the result as an enumeration object.

Is enum parse case sensitive?

The enum type to use for parsing. The string representation of the name or numeric value of one or more enumerated constants. true to read value in case insensitive mode; false to read value in case sensitive mode. When this method returns true , contains an enumeration constant that represents the parsed value.

Can enum be generic in C#?

Extra Credit: It turns out that a generic restriction on enum is possible in at least one other .


1 Answers

It is already implemented in .NET 4 ;) Take a look here.

MyEnum cal; if (!Enum.TryParse<MyEnum>("value1", out cal))    throw new Exception("value1 is not valid member of enumeration MyEnum"); 

Also the discussion here contains some interesting points.

like image 107
Tomas Vana Avatar answered Oct 02 '22 17:10

Tomas Vana