Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the " is " operator work internally

Tags:

.net

I want to compare the type of an object to a type to see if they are the same. I do not have the object, just the type of the object.

I can do type1 == type2 and get general equality

I can have a recursive loop where I repeat the above step for type1.BaseType until the BaseType is null.

I can do type1.GetInterface( type2.FullName ) != null to check if type2 is an interface of type1

If I put it all together, I get

if ( type2.IsInterface )
  return type1.GetInterface( type2.FullName ) != null;

while ( type1 != null ) {
  if ( type1 == type2 )
    return true;

  type1 = type1.BaseType;
}
return false;

Is that all the is keyword is. I cannot find the right keyword to plug into the Reflector search to find the function and a google search on "is" was not really helpful

like image 440
JDMX Avatar asked May 24 '10 15:05

JDMX


1 Answers

is (§14.9.10 of the standard) generally uses isinst, but it doesn't need to if the compile-time type is compatible via certain conversions.

A equivalent (in reverse) with a Type object is IsAssignableFrom. All of these are true:

"foo" is String;
"foo" is object;

typeof(String).IsAssignableFrom("foo".GetType());
typeof(object).IsAssignableFrom("foo".GetType());
like image 82
Matthew Flaschen Avatar answered Oct 18 '22 10:10

Matthew Flaschen