Boxing is copying the dice

7

Boxing is to turn value type into reference type, right?

But when we copy a reference type into another reference type , it just copies the address, not the value. But when I convert int to object for example and copy to another object, it is not working the same way.

Example:

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 10;
            object obj = x; //int vira reference type
            object obj2 = obj; //copia o endereço do obj pro obj2, certo?
            obj = 20; //modifica obj
            System.Console.WriteLine((int)obj2); //mostra obj2, era pra mostrar 20, nao? 
            //por que mostra 10?
            System.Console.ReadKey();
        }
    }
}
    
asked by anonymous 20.03.2015 / 17:20

2 answers

6

Boxing creates a new instance of a type by reference . Boxing does not change the immutability of the type of data being stored. On the contrary, she guarantees. If you have a changeable value type, which is rare, you can not change its value while it is cashed. First you would have to undock, change the desired member, and then box again.

What your code is doing is simply copying a value to a new object using a type by reference. You have a% w_th of% that actually carries a% w_th of%, so even though it is wrapped in a type by reference, deep down it has an internal representation of one type by value. So the moment you copy object to int is copying your reference as you would expect. At this point the two variables point to the same object in the heap . But this is going to change.

You're doing two boxing there in the code. When it does obj and then when obj2 . Yes, you are casing the value 20. 20 is a data of a type by value. It is not just variables that have type. In fact data has type, variables have the type of their value.

So you think obj = x and obj = 20 are pointing to the same object. And they are until you make a new boxing , then another object is created and that variable passes to another address and they become independent.

If the language did not operate in this way it would violate the immutability of the type.

    
20.03.2015 / 17:49
3

Very simply is the following: Boxing does conversion of the VALUE that is in the stack to heap and obviously Unboxing is the other way around. So let's go to the steps that .Net did:

  • int x = 10 // This is in the stack.
  • object obj = x // create an address in HEAP and put the value 10
  • object obj2 = obj; // At this time there are two "pointers" to the same address in HEAP
  • obj = 20 // Here is the secret, because at the moment this is being done in the new Boxing, ie creating the new address in the HEAP memory for the obj.
20.03.2015 / 17:49