Search code examples
c#ilvalue-typegettype

What is a better way to check that a given object is a particular value type?


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?


Solution

  • I am wondering why C# calls System.Type.op_Equality instead of ceq.

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

    Which one of the three would you use?

    If you want to know whether an instance is of a particular type, there is an operator specifically designed to solve that problem and that problem alone: is. Why would you ever not use the tool that was specifically designed to solve your problem? If you're replacing a roof and you have a choice between a roofing hatchet and a hammer, I hope you would use the roofing hatchet.

    Now, if you need to both do a type test and obtain the value then I would be inclined to use as because that is the operator specifically designed to solve that problem.