Thursday 26 May 2016

c# - How to limit a generic type parameter to System.Enum





Possible Duplicates:
Anyone know a good workaround for the lack of an enum generic constraint?
Create Generic method constraining T to an Enum






Is is possible to limit the generic type parameter [I don't know if that's the right name] to an Enum?




For example how do I do something like this?



//VB.NET
Function GetValues(Of T As System.Enum)(ByVal value As T) As IEnumerable(Of T)
Return [Enum].GetValues(value.GetType)
End Function

//C#
public IEnumerable GetValues(T value) where T : System.Enum
{

return Enum.GetValues(value.GetType());
}





Update



I eventually used Jon Skeet's Unconstrained Melody for that purpose. Thanks to you all for your contributions.


Answer




Unfortunately, you cannot - Microsoft closed this one out as a won't fix item.



You can treat enums as structs and use that as the constraint instead (I think that was how Jon Skeet did it in Unconstrained Melody?) but that is kind of unsightly.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...