7
Boxing is to transform value type in Reference type, right?
But when we copy a Ference type into another Reference type, it just copies the address and not the value. But when I convert int
for object
for example and copying to another object, 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();
}
}
}
So when I do obj = 20, does it create another int in the heap? And obj2 remains the "old int" address in the heap?
– RafaelMF
Exactly that. Because this is the function of Boxing. "Creates a new instance" is the key to understanding how it works. Note that today it is rarely necessary to Boxing in C#. This was important in C#1 before the Generic. It’s still in Java.
– Maniero
"Note que hoje raramente é necessário o boxing em C#"
not to mention the performance drop that this type of operation can cause. :)– rubStackOverflow