w00ngy
w00ngy

Reputation: 1828

Create a generic method with only certain types of enum as constraints

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.

Upvotes: 1

Views: 1333

Answers (1)

Hans Passant
Hans Passant

Reputation: 942020

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.

Upvotes: 1

Related Questions