95

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

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
diegogs
  • 2,036
  • 2
  • 16
  • 20

5 Answers5

191
bool result = (obj is MyClass); // Better than using 'as'
Ana Betts
  • 73,868
  • 16
  • 141
  • 209
57

The equivalent of Java’s obj.getClass().isInstance(otherObj) in C# is as follows:

bool result = obj.GetType().IsAssignableFrom(otherObj.GetType());

Note that while both Java and C# work on the runtime type object (Java java.lang.Class ≣ C# System.Type) of an obj (via .getClass() vs .getType()), Java’s isInstance takes an object as its argument, whereas C#’s IsAssignableFrom expects another System.Type object.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 1
    Note IsAssignableFrom takes a Type, not an object, so you need to actually do OtherObj.getType(). – FlySwat Nov 11 '08 at 23:25
  • 3
    Thanks Jon – and remember, this is a wiki! I don't resent people correcting my mistakes. – Konrad Rudolph Nov 11 '08 at 23:34
  • 1
    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 Nov 11 '08 at 23:37
  • Why is this method better then the "is" operator which is more readable? – Timothy Gonzalez Sep 21 '16 at 15:01
  • 1
    @TimothyGonzalez Because it does something different. It tests whether two *variables* have the same type. `is` required a type name, by contrast. This is what OP wanted: the equivalent of Java's `isInstance`. The other answer is simply wrong despite the ridiculous number of upvotes. – Konrad Rudolph Sep 21 '16 at 17:21
39

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;
}
Robert Gowland
  • 7,677
  • 6
  • 40
  • 58
2

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 :)

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
CodingWithSpike
  • 42,906
  • 18
  • 101
  • 138
2

Below code can be alternative to IsAssignableFrom.

parentObject.GetType().IsInstanceOfType(inheritedObject)

See Type.IsInstanceOfType description in MSDN.

Youngjae
  • 24,352
  • 18
  • 113
  • 198