I'm trying to write a validation to check that an Object instance can be cast to a variable Type. I have a Type instance for the type of object they need to provide. But the Type can vary. This is basically what I want to do.
Object obj = new object();
Type typ = typeof(string); //just a sample, really typ is a variable
if(obj is typ) //this is wrong "is" does not work like this
{
//do something
}
The type object itself has the IsSubClassOf, and IsInstanceOfType methods. But what I really want to check is if obj is either an instance of typ or any class derived from typ.
Seems like a simple question, but I can't seem to figure it out.
A derived class, in the context of C#, is a class created, or derived from another existing class. The existing class from which the derived class gets created through inheritance is known as base or super class.
How about this:
MyObject myObject = new MyObject();
Type type = myObject.GetType();
if(typeof(YourBaseObject).IsAssignableFrom(type))
{
//Do your casting.
YourBaseObject baseobject = (YourBaseObject)myObject;
}
This tells you if that object can be casted to that certain type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With