C#.NET - How can I get typeof() to work with inheritance?

Giffyguy picture Giffyguy · Aug 2, 2009 · Viewed 18.8k times · Source

I will start by explaining my scenario in code:

public class A { }

public class B : A { }

public class C : B { }

public class D { }

public class Test
{
    private A a = new A ( ) ;
    private B b = new B ( ) ;
    private C c = new C ( ) ;
    private D d = new D ( ) ;

    public Test ( )
    {
        // Evaluates to "false"
        if ( a.GetType == typeof(B) ) { } //TODO: Add Logic

        // Evaluates to "true"
        if ( b.GetType == typeof(B) ) { } //TODO: Add Logic

        // I WANT this to evaluate to "true"
        if ( c.GetType == typeof(B) ) { } //TODO: Add Logic

        // Evaluates to "false"
        if ( d.GetType == typeof(B) ) { } //TODO: Add Logic
    }
}

The important line to take notice of here is:

if ( c.GetType == typeof(B) ) { }

I believe that this will in fact evaluate to "false", since typeof(B) and typeof(C) are not equal to each other in both directions. (C is a B, but B is not necessarily a C.)

But what I need is some kind of condition that will take this into account. How can I tell if an object is a B or anything derived from it?

I don't care if it is an object DERIVED from B, so long as the base B class is there. And I can't anticipate what derived class might show up in my application. I just have to assume that unkown derived classes may exist in the future - and therefore I can only focus on making sure that the base class is what I am expecting.

I need a condition that will perform this check for me. How can this be accomplished?

Answer

cdm9002 picture cdm9002 · Aug 2, 2009

You can just use is:

if (c is B) // Will be true

if (d is B) // Will be false