What is the best way to check if a given object is a specific value type?

Below are 2 commonly used approaches for checking before unpacking.

myObject.GetType() == typeof(MyValueType)

IL_0001:  callvirt    System.Object.GetType
IL_0006:  ldtoken     UserQuery.MyValueType
IL_000B:  call        System.Type.GetTypeFromHandle
IL_0010:  call        System.Type.op_Equality


myObject is MyValueType

IL_0001:  isinst      UserQuery.MyValueType

Plus, I wonder why C # calls System.Type.op_Equalityinstead. ceqIs this equality check checked?

Update

Actually, there is a third way. (from C # 5.0 in a nutshell)

MyValueType? x = myObject as MyValueType?;

Then check x.HasValueand usex.Value

Which of 3 would you use?

+2
source share
2 answers

I am wondering why C # calls System.Type.op_Equalityinstead ceq.

Because types are compared by value, not by reference. There can be two types of objects in memory that are of the same type.

Which of the three would you use?

, , , : is. , ? , , , .

, , as, , .

+4

==, . , ?

, , , , , JIT , . , , isinst , JIT , ( ).

2-, , JIT , . , , , , JIT.

0

All Articles