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?
System.Type.op_Equality
ceq
Actually, there is a third way. (from C # 5.0 in a nutshell)
MyValueType? x = myObject as MyValueType?;
Then check x.HasValueand usex.Value
x.HasValue
x.Value
Which of 3 would you use?
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. , ? , , , .
is
, , as, , .
as
==, . , ?
==
, , , , , JIT , . , , isinst , JIT , ( ).
isinst
2-, , JIT , . , , , , JIT.