MarqueIV MarqueIV - 1 year ago 50
C# Question

Is there a notable difference between 'result is T' vs 'typeof(T).IsInstanceOfType(result)'?

Both of the following statements test if some object

is of type
. Is there any difference that one should be aware of performance-wise?

var result1 = x is T;
var result2 = typeof(T).IsInstanceOfType(x);


Answer Source

Since IsInstanceOfType is a method that takes an object, value types would be boxed. Operator is, on the other hand, will not perform boxing.

Using the first approach is better when you know T at compile time, either as a specific type or a generic type parameter. The second approach is for situations when your code obtains the type at run-time, because the first approach does not apply:

Type typeKnownAtRuntime = ...
var result2 = typeKnownAtRuntime.IsInstanceOfType(x); // This works
var incorrect = x is typeKnownAtRuntime;   // This does not compile