c# check for exact type

b.GetType() == typeof(A)

(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

Tags:

C#

Types