Tutorial :How to use the “where” keyword in C# with a generic interface, and inheritance


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?



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?


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  {  }  


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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »