C# Object Type Comparison


How can I compare the types of two objects declared as type.

I want to know if two objects are of the same type or from the same base class.

Any help is appreciated.


private bool AreSame(Type a, Type b) {


Best Solution

Say a and b are the two objects. If you want to see if a and b are in the same inheritance hierarchy, then use Type.IsAssignableFrom:

var t = a.GetType();
var u = b.GetType();

if (t.IsAssignableFrom(u) || u.IsAssignableFrom(t)) {
  // x.IsAssignableFrom(y) returns true if:
  //   (1) x and y are the same type
  //   (2) x and y are in the same inheritance hierarchy
  //   (3) y is implemented by x
  //   (4) y is a generic type parameter and one of its constraints is x

If you want to check if one is a base class of the other, then try Type.IsSubclassOf.

If you know the specific base class, then just use the is keyword:

if (a is T && b is T) {
  // Objects are both of type T.

Otherwise, you'll have to walk the inheritance hierarchy directly.