c# check for exact type

Viewed 8718

I want to check the type of an object. I only want to return true if the type is exact the same. Inherited classes should return false.

eg:

class A {}
class B : A {}

B b = new B();

// The next line will return true, 
// but I am looking for an expression that returns false here
if(b is A) 
5 Answers

(b is A) checks b for type compatibility with A which means it checks both the inheritance hierarchy of b and the implemented interfaces for Type A.

b.GetType() == typeof(A) on the other hand checks for the exact same Type. If you don't qualify the Types further (i.e. casting) then you're checking the declared type of b.

In either case (using either of the above), you will get true if b is the exact type of A.

Be careful to know why you want to use exact types in one situation over another:

  • For example, to check exact types defeats the purpose of OO Polymorphism which you might not wish to ultimately do.
  • However, for example, if you're implementing a specialized software design pattern like Inversion of Control IoC container then you will sometimes want to work with exact types.

Edit:

In your example,

if(b is A) // this should return false

turn it into an exact declared Type check using:

if (b.GetType() == typeof(A))

use:

if (b.GetType() == typeof(A)) // this returns false

Your code sample seems to be the opposite of your question.

bool isExactTypeOrInherited = b is A;
bool isExactType = b.GetType() == a.GetType();
bool IsSameType(object o, Type t) {
  return o.GetType() == t;
}

Then you can call the method like this:

IsSameType(b, typeof(A));
Related