3

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?

1
  • 1
    If you have type parameter in class Object, you should pass there a type. For me you need to make some interface, because you cannot pass there T Commented Jul 2, 2013 at 5:45

1 Answer 1

6

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.
Sign up to request clarification or add additional context in comments.

1 Comment

That worked. I had made a bit of a noob mistake and added the interface after the where T : class, rather than immediately after the class name, so it was not inheriting. Thanks for making me look at it again with a clearer idea of what I was going for though!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.