Below are the 2 commonly used approaches to check before unbox.
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 am wondering why C# calls System.Type.op_Equality
instead of ceq
Isn't that reference equality check?
Update
Actually, there is a 3rd way. (from C# 5.0 in a Nutshell)
MyValueType? x = myObject as MyValueType?;
Then check x.HasValue
and use x.Value
Which one of the 3 would you use?
myObject is MyValueType
. That's what theis
keyword is there for. I have faith that the compiler will choose a gode translation of it. Side note: With a value type, the two forms give the same result. But in other cases there's a difference, of course. For examplemyObject is IDisposable
works fine whilemyObject.GetType()
could never give an interface type or an abstract class. Another example,myObject is Func<object>
will give true for aFunc<string>
even if the typeFunc<>
is a sealed type. Covariance. – Buckman