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. 🙂
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
try/catchis definitely slower, since a thrown exception causes stack information to be gathered.as/isare for comparing to a type known at compile time and cater for inheritance (ie."string" is Objectreturnstrue)typeof/GetType()can be used for types known at runtime but do not cater for inheritance (ie."string".GetType() == typeof(Object)returnsfalse)Regardless, I think you probably want
as(orisif you don’t need the cast value)