C #: Prevalence when checking variable type

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

eg. using try/ catchversus using asversus using typeof.

Absolute measurements are not needed. :)

+3
source share
3 answers

try/ is catchdefinitely slower because the thrown exception throws up stack information.

as/ isare for comparison with a type known at compile time and satisfying inheritance (i.e. "string" is Objectreturns true)

typeof/ GetType()can be used for types known at runtime but not satisfying inheritance (i.e. "string".GetType() == typeof(Object)returns false)

, , , , as ( is, )

+5

, ; , . " ", , . . "is", "as" "GetType()", .

+2

If you just want to check this type, you have to go with the operator is.

+1
source

Source: https://habr.com/ru/post/1728322/


All Articles