How to do dynamically cast in C#

  • Thread starter Thread starter William Stacey
  • Start date Start date
W

William Stacey

Would this work for you (Note: typed from memory.) ?

if ( obj.GetType() == typeof(MyClass) )
{
MyClass myClass = (MyClass)object;
myClass.DoSomething();
}
else
{
//...
}
 
In C#, the method was dynamically invoked through reflection. But How
do we dynamically cast the return object to its own type? Here is the
sample code:

// dynamically invoke the method
Object obj = mi.Invoke(null, null);

// get the type of the returned object
Type MyType = obj.GetType();

// Question: Is there a way "(MyType)obj" to cast the obj dynamically
in runtime?

One option is through interface implementation, another option is to
let the obj implement IConvertible interface.

I am looking for any other simple solution. Does c# have any special
syntax to achieve this?

Your idea will be appriciated.
 
This probably means you are expecting the returned object to implement some
specific members. If so, create an interaface, and make sure that all
returned objects implement that interface. Then, you know that you can cast
to the interface and call whatever memeber you need to call.

-Rob Teixeira [MVP]
 
Back
Top