Boxing vs Unboxing

前端 未结 6 1905
暖寄归人
暖寄归人 2021-02-01 16:48

Another recent C# interview question I had was if I knew what Boxing and Unboxing is. I explained that value types are on Stack and reference types on Heap. When a value is cast

6条回答
  •  一生所求
    2021-02-01 17:00

    I think the answer to your question with unboxing is that: The result of an unboxing conversion is a temporary variable (more details: link).

    I think you were trying to do sth like:

    object a = new Point(10,10);
    object b = new Point(20,20);
    a = b;
    
    ((Point) b).X = 30; //after this operation also a.X should be 30
    

    The above code won't compile - details in the link above, and I think this is the answer to your question:

    I was expecting to see b == 2 as well, but it isn't, why? is it because the second boxing destroys and replaces the whole (a)-object on heap?

提交回复
热议问题