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
  • 28,010
  • 62
  • 221
  • 374

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
  • 151,543
  • 27
  • 246
  • 315
  • 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
  • 80,612
  • 21
  • 160
  • 208