I'm aware that multiple similar sounding questions have been asked before, however I still believe that this particular problem has not been solved yet.
There is a class Super and a generic class Foo<T> : Super, which both come from a third-party library. I need to extend the functionality of Foo<T> so I have this generic class:
public class Bar<T, U> : Foo<T> {
public void DoSomething() { ... }
// Other things that use T and U
}
I now want to have a collection(list) of "Bar's" and be able to call DoSomething on all of them. So logically, I dont care about the type argument of Bar, when calling the void method as it is irrelevant in that scenario.
Additionally the third-party library exposes methods such as:
public LibraryMethod(Super super) { ... }
And I need to be able to call that method with any of my "Bar's".
Not-A-Solution 1: Interfaces
The reason why I cant use an interface is, because the third-party library expects a Super in some of the methods it exposes, and an interface can be implemented by any class, so I cannot use my Bar's as Super's even though every Bar (no matter what its type arguments are) must be a Super. The interface essentially ruins the inheritance chain here and I can no longer pass my "Bar's" to methods expecting a Super.
Not-A-Solution 2: Non-Generic Base Class
Obviously I cannot make Bar<T, U> inherit from a non-generic base class, as per the same reason as above. It would ruin the inheritance chain as well.
Fictional Ideal Situation
In an ideal situation I could do something like this:
List<Bar<>> bars = new List<Bar<>>();
bars.Add(new Bar<Type1, Type2>());
bars.Add(new Bar<Type3, Type4>());
foreach (Bar<> bar in bars) {
bar.DoSomething();
}
LibraryMethod(bars[0]);
In short - you can't, C# does not support instantiating instances of open generic types and you can't limit the list to be both
SuperandIDoSomethinginterface at the same time. And you can't inheritBarfrom some non-generic type (which inheritsSuperand implementsIDoSomething) andFoo<>in addition.In this particular case you can add
AsSuperto your interface:Which should be easily implemented in
Bar:Which will allow you to type safely invoke
LibraryMethod: