Does the IS operator unbox value type or not?

I can't find an answer to the following question:

object o = 10; // Box
int i = (int)o; // Unbox

it's clear, but the following isn't clear

bool isInt = o is int; // Is the unbox here or not?

Answers


No, that's not unboxing - it's just checking whether the type is correct. Don't forget that there really is an object involved, with a type. Checking that type is basically the same operation regardless of whether the value is a boxed value type value or not. (There may be some optimizations feasible for value types or any sealed types, as there's no inheritance to consider, but fundamentally it's still checking the "type" part of an object header.)

One way to check that is to compile the code and look at the IL using ILASM:

// object o = 10
IL_0000:  ldc.i4.s   10
IL_0002:  box        [mscorlib]System.Int32
IL_0007:  stloc.0

// int i = (int) o;
IL_0008:  ldloc.0
IL_0009:  unbox.any  [mscorlib]System.Int32
IL_000e:  stloc.1

 // bool isInt = o is int
IL_000f:  ldloc.0
IL_0010:  isinst     [mscorlib]System.Int32

So it uses isinst - no unboxing is necessary.


Not only does it not require unboxing, logically, it can't.

Unboxing can succeed or fail, depending on whether the object really contains a value of the type we are going to try to unbox to.

Therefore, unboxing requires a check as to whether the object is of that particular type.

Therefore, if testing the type required unboxing, then since unboxing requires testing the type, we wouldn't be able to unbox until we'd first unboxed...

Therefore testing a type can't require unboxing.


As of C# 7, the is keyword has gained a new use case, in pattern matching as the type pattern. In this case, unboxing does occur e.g:

object o = 10;
if (o is int i) {
   // i is the unboxed value.
}

Obviously, this is a different case to the original post's where the value is purely being tested, as when using is as a pattern, you are actually assigning the value. Hence the need to unbox in this case.

To be clear - nothing has changed about the original o is int case - no unboxing will occur there, as per the old answers. The is keyword has just gained a new role.


Need Your Help

NSURLErrorDomain error code -999 in iOS

ios lua corona nsurl nsurlerrordomain

I've been trying to use Corona SDK's Facebook API to post the score on the game I'm developing on facebook. However, I'm having a problem with it. During the first time I try to post to facebook, I...

What are recursive arrays good for?

ruby arrays recursion

Ruby supports recursive arrays (that is, self-containing arrays):