is vs typeof

ilitirit picture ilitirit · Oct 8, 2008 · Viewed 118.8k times · Source

Which of these pieces of code is faster?

if (obj is ClassA) {}

if (obj.GetType() == typeof(ClassA)) {}

Edit: I'm aware that they don't do the same thing.

Answer

Jay Bazuzi picture Jay Bazuzi · Oct 8, 2008

Does it matter which is faster, if they don't do the same thing? Comparing the performance of statements with different meaning seems like a bad idea.

is tells you if the object implements ClassA anywhere in its type heirarchy. GetType() tells you about the most-derived type.

Not the same thing.