views:

1383

answers:

4

I know of is and as for instanceof, but what about the reflective isInstance() method?

+6  A: 
bool result = obj.GetType().IsAssignableFrom(otherObj.GetType());
Konrad Rudolph
Note IsAssignableFrom takes a Type, not an object, so you need to actually do OtherObj.getType().
FlySwat
Thanks Jon – and remember, this is a wiki! I don't resent people correcting my mistakes.
Konrad Rudolph
interesting... in java, the JVM treats "instanceof" specially, apparently its very very fast, which may explain why its unusually a keyword (there is also an isAssignable method in java).
Michael Neale
+1  A: 

just off the top of my head, you could also do:

bool result = ((obj as MyClass) != null)

Not sure which would perform better. I'll leave it up to someone else to benchmark :)

rally25rs
+2  A: 
bool result = (obj is MyClass); // Better than using 'as'
Paul Betts
+2  A: 

Depends, use is if you don't want to use the result of the cast and use as if you do. You hardly ever want to write:

if(foo is Bar) {
    return (Bar)foo;
}

Instead of:

var bar = foo as Bar;
if(bar != null) {
    return bar;
}