tags:

views:

228

answers:

2

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?

+6  A: 

It is already implemented in .NET 4 ;) Take a look here. Also the discussion here contains some interesting points.

Thomas Wanner
That link is to the non-generic `Enum.Parse` method. Did you mean to link to the new `Enum.TryParse<T>` method? http://msdn.microsoft.com/en-us/library/system.enum.tryparse%28VS.100%29.aspx
Sam
It is interesting that they constrained it to struct, new() instead of adding a new enum constraint to the language.
Yuriy Faktorovich
Sorry, I've fixed that already, that's exactly what I meant ;)
Thomas Wanner
The interesting thing is that they wouldn't even need to put a new constraint on the language - it would just be a method which couldn't actually be expressed in C#. The C# compiler can *obey* the constraints, even if you can't write them in C# :)
Jon Skeet
+2  A: 

Although constraining to System.Enum isn't allowed by C#, it is allowed in .NET and C# can use types or methods with such constraints. See Jon Skeet's Unconstrained Melody library, which includes code that does exactly what you want.

kvb
Humbug, I can't even plug my own library without someone getting there first ;)
Jon Skeet