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?
Parse(Type, String) Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
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.
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.
Extra Credit: It turns out that a generic restriction on enum is possible in at least one other .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With