Search code examples
c#castingreferenceboxingunboxing

Mechanism of Unboxing


When unboxing takes place there is the copy of boxed value into an appropriate variable type but what happens at the memory location of the boxed copy on heap. Is boxed copy remain at that location and cover memory on heap?


Solution

  • Is boxed copy remain at that location and cover memory on heap?

    Yes. After all, there could be other references to it:

    object o1 = 5;
    object o2 = o1;
    int x = (int) o1;
    x = 10;
    Console.WriteLine(o2); // Still 5
    

    Boxed values act like normal objects, in terms of being eligible for garbage collection when there are no more strong references to them.