views:

112

answers:

1

Hello!

I have some simple code which demonstrates my problem:

private void InitializeOther()
{
  List<Foo> list = new List<Foo>();
  Casting(list);
}

//in the "real" case I have no knowledge of o, other than it could be a List<>
private void Casting(object o)
{
  Type t = o.GetType();
  while (t.BaseType != typeof(Object))
  {
    if (t.IsGenericType && typeof(List<>) == t.GetGenericTypeDefinition())
    {
      //now I know that o is of type List<>. How can I now access List<> members from o?
      break;
    }
    t = t.BaseType;
  }
}

So, I can be sure that object o is of (or derived) from List<T>, but now I want to be able to access List<T> members on o, which means casting it up to List<Foo>. In my "real" case, I have no knowledge of Foo.

I'm pretty sure it can be done and if you know how to do it I'd be very grateful if you could share your knowledge with me!

A: 

A small hack will be to try and cast o to a non-generic IList, since List<T> implements both generic and non-generic interfaces. The same can be said of Collection<T> which is the most used base class for user collections.

If this is not an option, you can always get along with reflective method invocation (late binding): MethodInfo.Invoke(), etc.

Anton Gogolev
Ok, thanks, method invocation it is then
Shunyata Kharg