Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if an instance is of a certain Type or any derived types

Tags:

c#

types

casting

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.

like image 747
Eric Anastas Avatar asked Apr 16 '09 05:04

Eric Anastas


People also ask

Is derived type C#?

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.


1 Answers

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.

like image 170
Hadi Eskandari Avatar answered Oct 11 '22 12:10

Hadi Eskandari