What is the C# equivalent to Java's isInstance()?

C#ReflectionIntrospectionInstanceof

C# Problem Overview


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

C# Solutions


Solution 1 - C#

bool result = (obj is MyClass); // Better than using 'as'

Solution 2 - C#

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.

Solution 3 - C#

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;
}

Solution 4 - C#

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

Solution 5 - C#

Below code can be alternative to IsAssignableFrom.

parentObject.GetType().IsInstanceOfType(inheritedObject)

See Type.IsInstanceOfType description in MSDN.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondiegogsView Question on Stackoverflow
Solution 1 - C#Ana BettsView Answer on Stackoverflow
Solution 2 - C#Konrad RudolphView Answer on Stackoverflow
Solution 3 - C#DavidView Answer on Stackoverflow
Solution 4 - C#CodingWithSpikeView Answer on Stackoverflow
Solution 5 - C#YoungjaeView Answer on Stackoverflow