5

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.

FerranB
  • 35,683
  • 18
  • 66
  • 85

4 Answers4

10

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.

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
5

in your specific instance:

bool isExactlyA(X obj)
{
   return obj.GetType() == typeof(A);
}
snicker
  • 6,080
  • 6
  • 43
  • 49
2

I see...

control.GetType() ==  typeof(Label)
FerranB
  • 35,683
  • 18
  • 66
  • 85
0

More information about the typeof and is operators, as well as the GetType method.

Community
  • 1
  • 1
jasonh
  • 29,297
  • 11
  • 59
  • 61