FerranB
FerranB

Reputation: 36807

How to check if an object its *exactly* a class, not a derived one?

There is any way to determine if an object is exactly a class and not a derived one of that?

For instance:

class A : X { }

class B : A { }

I can do something like this:

bool isExactlyA(X obj)
{
   return (obj is A) && !(obj is B);
} 

Of course if there are more derived classes of A I'd have to add and conditions.

Upvotes: 5

Views: 2636

Answers (4)

Eric Lippert
Eric Lippert

Reputation: 660058

Generalizing snicker's answer:

public static bool IsExactly<T>(this object obj) where T : class
{
  return obj != null && obj.GetType() == typeof(T);
}

and now you can say

if (foo.IsExactly<Frob>()) ...

Caveat: use extension methods on object judiciously. Depending on how widely you use this technique, this might not be justified.

Upvotes: 11

snicker
snicker

Reputation: 6148

in your specific instance:

bool isExactlyA(X obj)
{
   return obj.GetType() == typeof(A);
}

Upvotes: 5

FerranB
FerranB

Reputation: 36807

I see...

control.GetType() ==  typeof(Label)

Upvotes: 2

Related Questions