Casting types when having the System.Type

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello,

Is there a way to cast to another type when all we have is the System.Type.

Say, if we have:
Class MyBaseClass;
Class MyDerivedClass:MyBaseClass;

instead of:
MyDerivedClass derivedObject = new MyDerivedClass();
MyBaseClass baseObject = (MyBaseClass) derivedObject;

something like this:
public object CastToBaseClass( object someObject )
{
System.Type baseType = someObject.GetType().BaseType;

//now what? :S

object baseObject = (/* what goes here?*/) someObject;
//in my dreams: ... keyword "classof", inverse of "typeof"
// object baseObject = (classof( baseType ) ) someObject; :) :) :)
}

Anything like that in the framework?

Thanks
 
Abelardo,

No there is not. How would you know what to call at compile time? You
will have to use reflection to do what you want.

Either that, or expose an interface that the type implements, and cast
the instance to that interface.

Hope this helps.
 
but if there is two versions of one method created using "new" keyword and
you want to call base class's implementation?
 
If you want to call the base class implementation, then get the type of
the base class and then reflect to get the MethodInfo of the shadowed
method.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top