C#: Expensiveness in checking the type of a variable

c

How expensive is it to check the type of a variable in C#?

E.g. using try/catch vs. using as vs. using typeof.

Absolute measurements are not necessary. 🙂

Best Answer

try / catch is definitely slower, since a thrown exception causes stack information to be gathered.

as/is are for comparing to a type known at compile time and cater for inheritance (ie. "string" is Object returns true)

typeof/GetType() can be used for types known at runtime but do not cater for inheritance (ie. "string".GetType() == typeof(Object) returns false)

Regardless, I think you probably want as (or is if you don't need the cast value)