Can `typeof(T).IsAssignableFrom(x.GetType())` be safely rewritten as `x is T`?

Viewed 1048

Note: This is not a duplicate of "Use of IsAssignableFrom and “is” keyword in C#". That other question asks about typeof(T).IsAssignableFrom(type)), where type is not an object but a Type.

This seems trivial — I can hear you saying, "Just call x.GetType()!" — but due to the COM-related corner case mentioned below, that call causes problems, which is why I'm asking about the rewrite.

… or are there rare special cases where the two might give different results?

I stumbled upon a type check of the form:

typeof(TValue).IsAssignableFrom(value.GetType())

where TValue is a generic type parameter (without any constraints) and value is an object.

I am not entirely sure whether it is safe to rewrite the above simply as:

value is TValue

To my current knowledge, the two tests are equivalent with the exception of COM objects. is should trigger a proper QueryInterface, while IsAssignableFrom might get confused by the __ComObject RCW wrapper type and report a false negative.

Are there any other differences between is and the shown use of IsAssignableFrom?

2 Answers
Related