C# Generics - a generic type constraint

Keywords: c# generics


I have the following generic type hierarchy:

interface IGenericInterface<TId, TValue>

class A : IGenericInterface<long, string>

I want to design a generic type that takes IGenericInterface as type. The solution allowed by the compiler is:

class SomeType<TType, TId, TValue> where TType : IGenericInterface<TId, TValue>

When I need to inherit such a type, I need to specify:

class Derived : SomeType<A, long, string>

This looks like a redundancy to specify 2nd and 3rd type arguments, because class A is already of IGenericInterface<long, string>.

Is there a way to achieve what I want - Derived class in a more elegant way?


You could add an intermediate interface and have SomeType constrain against that instead. Something like:

interface IA : IGenericInterface<long,string> { }

class A : IA {}

class SomeType<TType> where TType : IA { }

class Derived : SomeType<A> { }