C# generics - Can I make T be from one of two choices?

Jean-Bernard Pellerin picture Jean-Bernard Pellerin · Jun 21, 2010 · Viewed 11.9k times · Source

Suppose I have the following class hierarchy:

Class A {...}

Class B : A  {...}

Class C : A {...}

What I currently have is

Class D<T> where T : A {...}

but I'd like something of the form

Class D<T> where T in {B,C}

This is due to some odd behavior I'm not responsible for where B and C have common methods which aren't in A, but it would be nice to be able to call them in D on T.

Note: I don't have access to A,B or C to edit them

Answer

Grzenio picture Grzenio · Jun 21, 2010

You need to define an interface for the common methods that are in B and C (lets call it Ibc), make B and C implement this interface, and then you can write:

Class D<T> where T : A, Ibc {...}