diegogs diegogs - 2 months ago 14
C# Question

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

I know of

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

Answer

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.