F
F
footballer2018-03-17 23:36:13
.NET
footballer, 2018-03-17 23:36:13

Why is there no wrapping in var a = new int[1] {5}?

Boxing is said to be a heavy operation due to the fact that the structure is copied from the stack to the heap.
The following code is given as an example of packing:
var a = new object[1] {5};
that is, when we put an int into an array of objects.
But even if we create an array of ints like this:
var a = new int[1] {5} ;
then all the same, our int 5 must be copied to the heap, because The memory for the array is allocated on the heap. But why in this case is it not considered that this is not a package, and it is considered that this is not a heavy operation?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
eRKa, 2018-03-18
@kttotto

I think you misunderstood something. An array is a reference type and in case
the value of the variable awill lie on the stack, but the value will be a reference to a place on the heap pointing to an array of ints. The same applies to
Packing will happen with values ​​that are on the stack, and then copied to the heap. For example like this

int a = 5;
var b = (object)a;

In the first line, we put a five on the stack, and in the second line, we put this five on the heap. The variable bwill be on the stack, the value of which will point to the address on the heap where the type is object, with the value valueequal to 5. And the fact that the object will have an int field does not mean that it will be on the stack.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question