Answer the question
In order to leave comments, you need to log in
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
I think you misunderstood something. An array is a reference type and in case
the value of the variable a
will 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;
b
will be on the stack, the value of which will point to the address on the heap where the type is object
, with the value value
equal 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 questionAsk a Question
731 491 924 answers to any question