What does Box and Unbox mean? [duplicate]
Asked Answered
L

3

12

Possible Duplicates:
Why do we need boxing and unboxing in C#?
What is boxing and unboxing and what are the trade offs?

In C# what does "Box and Unbox" mean?

Here's an extract from MSDN where I found the text.

But this convenience comes at a cost. Any reference or value type that is added to an ArrayList is implicitly upcast to Object. If the items are value types, they must be boxed when they are added to the list, and unboxed when they are retrieved. Both the casting and the boxing and unboxing operations decrease performance; the effect of boxing and unboxing can be very significant in scenarios where you must iterate over large collections.

Lorie answered 25/1, 2011 at 14:33 Comment(2)
possible duplicate of Why do we need boxing and unboxing in C#? and Use cases for boxing a value type in C#?.Officeholder
Also duplicate of #13555Conrado
S
28

Here is a more detailed explanation that looks at the internal of Common Language Runtime.

First, let's make the difference between value types and reference types:

  • A value type is held on the stack and a copy of it is passed to called methods
  • A reference value is held in the managed heap and the stack holds only a pointer (reference) to its location. The location, and not the object, is passed to called methods

If you don't know what the stack is (don't be offended), it's a memory area that holds local variables in a method and addresses of caller functions used for return instruction (just to be brief and provide a general answer). When you call a method, a sufficient area on the stack is statically allocated to it, so stack allocation is always called static allocation.

The heap, instead, is a memory area separated from the stack, property of the running process, in which allocation must be first demanded to the operating system, and that's why it's called dynamic allocation (if you don't run in an if statement, for example, memory may not be allocated for your process, instead stack is always allocated).

Just to make a final example on heap and stack: in languages such as C++, declaring int[100] a; statically allocates 100*8 bytes on the stack (64-bit system assumed), while int* a = new int[100]; declares a 8 bytes (on 64-bit systems) area on the stack AND requests 800 more bytes on the heap, if and where available.

Now let's talk about C#:

Boxing

Since int is a value type, and is allocated on the stack, when you cast it to object or any other reference type (actually there is no other reference type from which int can inherit, but it's a general rule) the value must become necessarily a reference type. So a new area on the heap is allocated, the object is boxed inside it and the stack holds a pointer to it.

Unboxing

Just the opposite: when you have a reference type, such as object, and want to cast it to a value type, such as to int, the new value must be held on the stack, so CLR goes to heap, un-boxes the value and copies it to the stack.

In other words

Remember the int[] and int* examples? Simply, when you have int in C#, the runtime expects its stack location to hold the value but instead when you have object, it expects its real value to be in the heap location pointed by the stack.

Shipment answered 25/1, 2011 at 14:50 Comment(2)
A storage location (parameter, variable, or field) of a struct (value) type holds all of its data in fields that are stored within the storage location itself. Automatic variables and parameters are generally held on the stack; class fields are always held on the heap; struct fields are held within the struct that contains them. By contrast, the only thing held within a storage location of reference type is either a reference to a heap object that actually holds the data, or a null reference.Adversity
One important note about the boxing process: when it is happening the copy of the value is actually passing but not the value itself, which is kind of similar when you call a method that accepts a value type as a parameter.Babul
P
1

There are two different types in .net Framework.

ValueTypes such as int, double, single

ReferenceTypes ArrayList List and many, many more

Variables of type ValueTypes are stored in Stack ReferenceTyped variables are stored in heap

Variables of type ValueTypes store the VALUE ReferenceTyped variables store the REFERENCE to a value

so if you copy a ValueType variable - there is a real copy of a value but if you copy a ReferenceType variable - you will get an additional reference to the SAME variable.

Boxing in your question means, that a valueType Variable (e.g. int) will be handled liked a reference Type Variable - .net gives it into a new box. So it will be encapsulated within the heap and there will be reference(s) to it.

In case you want the value to be again in a valueType Variable you have to unbox it (take it out of the box). So the value will be taken out of the heap - and stored/given to the stack once again.

Periphrastic answered 25/1, 2011 at 14:49 Comment(4)
"Variables of type ValueTypes are stored in Stack" No, usually not. They're usually stored inside an object of reference type, living on the heap.Discoverer
@BenVoigt according to Eric Lippert's Blog "in the Microsoft implementation of C# on the desktop CLR, value types are stored on the stack when the value is a local variable or temporary that is not a closed-over local variable of a lambda or anonymous method, and the method body is not an iterator block, and the jitter chooses to not enregister the value" - so I think my answer should be acceptablePeriphrastic
Your answer makes a universal statement, about something that is not even close to universal.Discoverer
msdn.microsoft.com/en-us/library/yz2be5wk.aspx When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap.Zagreus
G
0

ArrayList stores only Objects. For a reference-type (like String) this is no problem but for a ValueType (int, DateTime, ..) it is.

These valuetypes need to be converted to an object before you can store them as plain Object. This "converting to object" is called "boxing" and takes a little bit of time.

When you read the value back, you need to convert from Object to int (or whatever it was). This is called "unboxing".

Germander answered 25/1, 2011 at 14:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.