Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the IS operator unbox value type or not?

Tags:

c#

.net

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?
like image 230
Viacheslav Smityukh Avatar asked Aug 31 '12 20:08

Viacheslav Smityukh


People also ask

What is boxing and unboxing in reference type variable?

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the common language runtime (CLR) boxes a value type, it wraps the value inside a System. Object instance and stores it on the managed heap. Unboxing extracts the value type from the object.

Is the process where the reference type is converted back into a value-type?

The process of converting a Reference Type variable into a Value Type variable is known as Unboxing. It is an explicit conversion process.

Which of the following is implicit boxing?

Boxing is the process of converting a value type to the object type or any interface type implemented by this value type. Boxing is implicit.

Why boxing and unboxing is needed in C#?

Boxing and unboxing enables a unified view of the type system wherein a value of any type can ultimately be treated as an object. With Boxing and unboxing one can link between value-types and reference-types by allowing any value of a value-type to be converted to and from type object.


1 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.

like image 121
Jon Skeet Avatar answered Oct 05 '22 22:10

Jon Skeet