29

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) 
shA.t
  • 16,580
  • 5
  • 54
  • 111
Tarscher
  • 1,923
  • 1
  • 22
  • 45
  • Your example and your question don't make sense together. You say you only want to return true if the type is inherited, but then show that an inherited comparison should return false. – Russell Steen Jan 29 '10 at 16:17
  • I think you mean you only want to return true when it's the exact same type (not inherited). Otherwise the comment in your code is wrong. – rui Jan 29 '10 at 16:17

5 Answers5

55
b.GetType() == typeof(A)
ChaosPandion
  • 77,506
  • 18
  • 119
  • 157
14

(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))
John K
  • 28,441
  • 31
  • 139
  • 229
9

use:

if (b.GetType() == typeof(A)) // this returns false
Alex LE
  • 20,042
  • 4
  • 30
  • 28
4

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

bool isExactTypeOrInherited = b is A;
bool isExactType = b.GetType() == a.GetType();
herzmeister
  • 11,101
  • 2
  • 41
  • 51
3
bool IsSameType(object o, Type t) {
  return o.GetType() == t;
}

Then you can call the method like this:

IsSameType(b, typeof(A));
rui
  • 11,015
  • 7
  • 46
  • 64
  • 1
    This doesn't work. It is perfectly legal -- rare, but legal -- for two different types to have the same full name but be different types. Why not just compare o.GetType() to t, rather than going through the names? (If you are in the unfortunate situation of having two types with the same full name and you need to use them in the same assembly then you can use an imported assembly alias to tell them apart.) – Eric Lippert Jan 29 '10 at 16:59