1

There are lots of questions floating around about how to create an Enum constraint for generic types. ex1, ex2, ex3 etc.

I was curious if it were possible to go one step further and require only certain locally defined enums as constraints to your generic method.

Currently, I'm using the suggested solution of using structure, Iconvertible constraints on the generic type to handle allowing enums for generic types. That looks something like this in vb.net:

Private Function MyMethod(Of T As {Structure, IConvertible})(ByVal myEnum As T) As Object
     '...
End Function

Now what would happen if I wanted to further force the constraint to only two of my enums, defined as follows:

Public Enum EnumOne
    Height
End Enum

Public Enum EnumTwo
    Width
End Enum

I haven't been able to figure out the syntax yet.

Although I'm programming in VB.net, C# answers are welcome as well.

Community
  • 1
  • 1
w00ngy
  • 1,646
  • 21
  • 25

1 Answers1

1

No, you cannot constrain the type argument like that, these enum types have nothing in common. There is not much value in a generic function that could handle only two type argument types, it is much simpler to just provide two non-generic overloads of the functions:

Private Function MyMethod(ByVal value as EnumOne) As Object
     '' etc
End Function

Private Function MyMethod(ByVal value as EnumTwo) As Object
     '' etc
End Function

With perhaps another private method that provides the common implementation for these functions.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • Even when code uses a small number of discrete types, using generics may help avoid duplication. For example, one may have some code that performs some complicated computations, and want to be able to exercise it on variables of type `double` and `Decimal` (and perhaps `float`). If `PerformComputations` has some static delegates `Func Sum, Difference, Product, Quotient;` etc. and internally defines operator overloads that use those, it may be possible to avoid having to write two or three copies of one's computation code to handle different types. – supercat Jul 01 '13 at 17:36