tags:

views:

107

answers:

4

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.

+3  A: 

in your specific instance:

bool isExactlyA(X obj)
{
   return obj.GetType() == typeof(A);
}
snicker
typeof requires a type not a class
FerranB
woops, good point.
snicker
+2  A: 

I see...

control.GetType() ==  typeof(Label)
FerranB
That's correct. IF you do typeof(control), you always get Control.
Steven Sudit
Aye, I added your method in a working manner =]
snicker
+7  A: 

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
what is 'x' in this code?
pradeeptp
A typo. ----------------------
Eric Lippert
@eric: just use some padding space within the message bounds to overcome the minimum length limit :)
leppie
@me: that doesnt seem to work no more :(
leppie
This is for .net 3.x
FerranB