'Using "is" operator to compare two variable types in C# [duplicate]

I know that I can easily compare two variable types like this:

i.GetType() == i2.GetType())

Also, this kind of comparison works fine:

int i = 0;
if(i is int){}

So, why something like this does not work, and I get error that "i2 is trying to be used as a Type"?

int i = 0;
int i2 = 0;
if(i is i2.GetType()){}

Similar, such construction doesn't work:

typeof(str.GetType())



Solution 1:[1]

There's a difference between a compile time type (using the type name, like int) and a runtime variable which holds information about a type (a variable of type System.Type, such as what's returned by i2.GetType()). You seem to be confusing those two.

If you want to see if a variable is of a particular type, and you know what that type is at compile time, use is.

if (i is int)

If you don't know the comparison type at compile time, but instead at runtime, you need to use GetType.

For just straight-up equality comparison:

if (i.GetType() == i2.GetType())

And for testing if i inherits/implements from whatever i2 is

i2.GetType().IsAssignableFrom(i.GetType())

is only works when you know the type (and with newer features of c#, other aspects of the type's schema) at compile time.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1