Reputation: 877
I have an object taking a type parameter - call it Object<T>
- and need to be able to add a number of objects with different type parameters to a list, as below:
var obj1 = new Object<SomeType>();
var obj2 = new Object<SomeOtherType>();
var list = new List<Object<WhatGoesHere>{ obj1, obj2 };
I know I could use an interface if it was just a list of different objects but that does not seem to apply to a list of objects with different type parameters so I am interested to know what my options are here?
Upvotes: 3
Views: 1514
Reputation: 64628
It's usually best to create an interface. I have interfaces on most of my generic classes, to use them without knowing the generic argument.
interface IFoo
{
object UntypedBlah(object arg);
}
class Foo<T> : IFoo
{
object UntypedBlah(object arg)
{
return Blah((T)arg);
}
T Blah(T arg)
{
//...
}
}
List<IFoo> foos = new List<IFoo>();
foos.Add(new Foo<int>());
foos.Add(new Foo<string>());
Upvotes: 6