lundi 5 juin 2017

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

… 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?





Aucun commentaire:

Enregistrer un commentaire