How to do generic polymorphism on open types in C#?
I have an interface like:
interface IFoo<in T> {
...
}
And I want to have a collection of those classes WITHOUT forcing a specific generic parameter for all collection elements, like:
class IFooCollection {
List<IFoo<?>> _items;
public IFooCollection(List<IFoo<?>> items)
{
_items = items;
}
...
}
Since you don't want to force a specific type, make an abstract class
or an interface
this way:
interface IFoo { }
And inherit it in your type-specific Foo (with generic parameters), like:
interface IFoo<T> : IFoo {}
This way you can just have a List<IFoo>
and add IFoo<T>
instead.
More examples:
class FooCollection {
private List<IFoo> _collection;
public FooCollection()
{
_collection = new List<IFoo>();
}
public void Add(IFoo foo)
{
_collection.Add(foo);
}
public void Remove(IFoo foo)
{
_collection.Remove(foo);
}
}
As indicated by @IvMisticos, to be able to do pseudo generic polymorphism on open type, you can write:
interface IFoo
{
}
interface IFoo<in T> : IFoo
{
}
class FooCollection
{
List<IFoo> _items;
public FooCollection(List<IFoo> items)
{
_items = items;
}
}
var item1 = some instance of IFoo<int>;
var item2 = some instance of IFoo<double>;
var item3 = some instance of IFoo<string>;
var list = new List<IFoo> { item1, item2, item3 };
var col = new FooCollection(list);
Since there is no diamond operator <>
to allow true generic polymorphism on open types in C#, it is the only thing you can do, as I know.
I really dislike this hack that smells bad.
What exactly is an "open generic type" in .NET?
Generics -Open and closed constructed Types