Let’s say I have a generic class:
public class MyGenericClass<T> {
...
}
Now inside this class, I want to have a method that allows me to interact with another generic, which could be of generic type T or any superclass of T, for example:
public void DoSomething<T1>(List<T1> things)
where T : T1 // of course this won't compile
{
...
}
How would you do this?
You can’t, I’m afraid. The closest you could come would be to have a method in a non-generic class – possibly an extension method:
That’s fine, because it’s introducing both type parameters at the same time.
Of course, an alternative would be to keep the method as an instance method within
MyGenericClass<T>, without the constraint, and check the constraint at execution time. That would be unfortunate in terms of the compile-time safety and general declarative nature of generics, but it may end up working out better for you.