tags:

views:

89

answers:

3

What I want to achieve is this:

  • Declare a generic class (<T>),
  • Have the "T" restricted to types that implement IMySpecialInterface<X> (where "X" is not a known type),
  • And have the class inherit from a parent class.

to give an incorrect example:

public class MyClass<T> : MyParentClass where T : IMySpecialInterface<X>
{
...
}

What is the proper syntax to achieve this?

Thanks.

+3  A: 

You will need to define a non-generic version of IMySpecialInterface<X>, unless you supply a secondary type for MyClass. The whole thing would look like this then:

public interface IMySpecialInterface
{
}

public interface IMySpecialInterface<X> : IMySpecialInterface
{
}

public MyClass<T> : MyParentClass where T : IMySpecialInterface
{
}
Femaref
Shouldn't it be public interface `IMySpecialInterface<X> : IMySpecialInterface` for the second line?
Scott Chamberlain
of course. mea culpa.
Femaref
+7  A: 

You can't use generics without knowing the types, unless you created the type at runtime.

Your best fit would be:

public class MyClass<T, U> : MyParentClass where T: IMySpecialInterface<U>
{

}

UPDATE or could you potentially use dynamic?

Matthew Abbott
this doesn't achieve the requirements. X isn't known when creating the class.
Femaref
Then he can't do it, unless he dynamically creates the type at runtime. The compiler can't compile unknowns.
Matthew Abbott
that's why you need a non-generic version of the interface, see [my answer](http://stackoverflow.com/questions/3419176/how-to-use-the-where-keyword-in-c-with-a-generic-interface-and-inheritance/3419199#3419199) ;)
Femaref
+4  A: 
public class MyClass<T, X> : MyParentClass where T : IMySpecialInterface<X>
{
...
}
Lee
this doesn't achieve the requirements. X isn't known when creating the class.
Femaref