GP24
GP24

Reputation: 877

How to make a list of objects with generic type parameters

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

Answers (1)

Stefan Steinegger
Stefan Steinegger

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>());
  • You could also make it covariant. (The interface would have a covariant generic argument. It depends on the members you need on the interface if this makes sense or not.)
  • Instead of having "untyped" members, you could give them the same name and implement them explicitly. But sometimes you get into troubles when having complex interface and class hierarchies, and it might be easier to just give them a different name.

Upvotes: 6

Related Questions