tags:

views:

119

answers:

2

I have a generic class, but I want my type to be forced to inherit from either one or the other interface. For example:

public class MyGeneric<T> where T : IInterface1, IInterface2 {}

The above will force T to inherti from both IInterface1 and IInterface2 but can I force T to inhert from IInterface1 OR IInterface2 (or both)?

A: 

No, you can't do this. It simply doesn't make sense.

The best you could do would be to create 2 empty subclasses of your generic class, and make the generic class abstract. Like this:

abstract class MyGenericClass<T>
{
  ...
}

public class MyClass1<T> : MyGenericClass<T>, IInterface1
{ }

public class MyClass2<T> : MyGenericClass<T>, IInterface2
{ }
Orion Edwards
+3  A: 

Define a base interface -- it doesn't even have to have any members and let both Interface1 and Interface2 extend it. Then scope T to be of the base interface type. This only works if you want to have the generic derive from your interfaces, not any of the existing ones in the framework.

public interface BaseInterface
{
}

public interface Interface1 : BaseInterface
{
    void SomeMethod();
}

public interface Interface2 : BaseInterface
{
    void SomeOtherMethod();
}

public class MyGenericClass<T> where T : BaseInterface
{
    ...
}

var myClass1 = new MyGenericClass<Interface1>();

var myClass2 = new MyGenericClass<Interface2>();
tvanfosson