Casting when type to cast to is only known at runtime

Lets say I have 2 types - TypeA and TypeB.  There are times that I need to handle these types generically as objects so I can cast to an object no problem.  However when I need to cast back to a specific type from an object I have some issues.  I can do the following OK if I know at design time the type of the object:

(TypeA)SomeObject

However, if I only know the type of the object at runtime, how do I define the cast at design time.  If  I want to cast back to the actual object type which I can get from Type t = SomeObject.GetType() how can I declare the cast to t in my code  

(t)SomeObject fails at compile time

Any help is appreciated.

 



Answer this question

Casting when type to cast to is only known at runtime

  • madhatt30

    So you have a list of each object, and they are all stored in a list together If TypeA/TypeB/TypeC etc had a base class of Type, couldn't you then do List<Type> Or is that not viable Is the problem that you don't know what is in each list when you first pull it out What if you used a map, and used the key to store the type of each list

  • Troy Neville

    The types are actually generic list i.e. List<TypeA> and List<TypeB> so the base type is object.  I though I may be able to use List<Object> but it seems I can't

    I actually have about a dozen types of list to deal with so the above would get a little long.

     


  • goranV

    If you want to find out if an object is of TypeA or TypeB, you can do this

    TypeA a = myObj as TypeA;

    if ( a != null)
    {

    }
    else
    {
      TypeB b = myObj as TypeB;
    }

    If you have a lot of types to work with, this would obviously get tedious.

    The objects don't have a common base type

  • Hong Ju Zhang

    TypeA and TypeB do have a common base type (TypeC) so I thought I could cast both lists to List<TypeC> but I get a compiler error saying I cannot do this


  • Casting when type to cast to is only known at runtime