1

How to use(constraint) an Enumeration as a generic parameter in .NET?

I used somthing like

Public Function GetEnumStringValues(Of EType As {Structure, _ 
                   IComparable, IConvertible, IFormattable})() As List(Of String)

but this is not good.

serhio
  • 27,402
  • 58
  • 213
  • 366

2 Answers2

3

You can use enum types as generic parameters to a method (for example List<EType>, but you cannot restrict generic parameters to only be enum types.

However, there are tricks you can use to almost guarantee that only enums get used in your methods:

public static T ParseEnum<T>(this string enumValue)
    where T : struct, IConvertible

See Converting string back to enum for a more full explanation and code samples.

Community
  • 1
  • 1
StriplingWarrior
  • 142,651
  • 26
  • 235
  • 300
  • sorry for my English: "there are tricks you can use to *almost* guarantee", almost, but not totally. – serhio Jul 05 '11 at 09:08
2

Not possible I am afraid.

It has been requested though.

Jon Skeet has a workaround for it.

Aliostad
  • 78,844
  • 21
  • 155
  • 205