I have an inelegant solution for what I need, but am looking for an elegant solution to replace it.
The following code doesn’t compile, but represents what I would like to do:
interface IWebService
{
}
abstract class BaseClient<T>
{
}
class SpecializedClient : BaseClient<IWebService>
{
}
class ClientHelper<T> where T : BaseClient<*>
{
}
Where the T in ClientHelper<T> is any class that extends BaseClient regardless of the templated type passed in.
The inelegant solution I found is:
class ClientHelper<T, U> where T : BaseClient<U> {}
The reason this becomes inelegant is my project ends up with a class similar to:
class MyClass<A, B, C, D, E, F, G> where A : MyBaseClass<B, C, D, E, F, G>
All the way down to the base class that takes a single type. Is this simply the cost of having a complex inheritance tree of generic classes or is there a simpler way to do this while retaining type restrictions on the templated types?
Your “inelegant” solution is the right one if the public interface of BaseClient exposes it’s generic type parameter in any way.
So assuming
BaseClientis not as you defined it:Then T is part of the public interface contract of
BaseClient, and therefore part of the public interface contract ofClientHelper(again, assuming thatBaseClient<U>is exposed via the interface of ClientHelper).On the other hand, let’s assume it actually is as your example puts it:
In that case, you can do:
and
ClientHelperbecomes: