Generics: where T - TypeA OR TypeB

When working with generics, we can do where T: TypeA, TypeB

, which means that T has to implement both TypeA and TypeB. But can OR be used in this expression? For example where T: TypeA || TypeB

? Is there any way to do this?

+3


source to share


2 answers


It is not possible and it would not make sense. You can never rely on T

having specific members, because it could be A or B. All members are optional.



Of course, it is possible that this feature is there, but it goes against the spirit of generics. This would only be useful in a reflection situation.

+8


source


The only way to achieve this is to do TypeA

and TypeB

inherit or implement the same parent class or interface. For example:

public interface IParent
{
}

public class TypeA : IParent
{
    //snip
}

public class TypeB : IParent
{
    //snip
}

      



Then you can use

public class Blah<T> where T: IParent
{
}

      

+7


source







All Articles