55502f40dc8b7c769880b10874abc9d0

How can I make this work?

Type type1 = SomeMethodThatReturnsAType();
Type type2 = SomeOtherMethodThatReturnsAType();

object obj = Activator.CreateInstance(type1);

//what I need now is obj cast to the type represented by type2, (type2)obj;

Refactorings

No refactoring yet !

D41d8cd98f00b204e9800998ecf8427e

bob

July 1, 2010, July 01, 2010 06:33, permalink

1 rating. Login to rate!

That doesn't make sense. Casts are a compile-time thing. All a "cast" does is (1) it inserts a check of the dynamic type of the object at runtime. This you can do with "type2.IsInstanceOfType(obj)"; (2) it allows you to assign the object reference to a variable of type2 and call the methods of type2 on the object, but of course you can't have these because you don't have the type of type2 at compile time. If you want to call type2's methods on obj, you will need to use reflection to get the methods out of type2 and then invoke them on obj.

Your refactoring





Format Copy from initial code

or Cancel