0

Richter "CLR via C#" famous book

I understand, when do unboxing, it returns pointer to unboxed value on heap, but i cant get pointer in C#, so there is copy of fields from heap to stack done (answered here).

But, when i do

Console.WriteLine(v + ", " + (Int32)o);

so, when i do unboxing of object "o", only pointer passed, without copy. "...This requires an unboxing operation (but no copy operation)..." (Richter, page 129)

Now, my question is: when return pointer to unboxed value on heap and when it also copied to the stack?

Thanks

P.S.: code:

        Int32 v = 5;
        Object o = v;
        Console.WriteLine(v + ", " + (Int32)o);
Community
  • 1
  • 1
zzfima
  • 1,528
  • 1
  • 14
  • 21

1 Answers1

1

The unbox itself doesn't copy the value. But the value is nonetheless copied when it's used. In your example from Richter's book, the box operation that immediately follows copies the value into a new boxed value.

Philippe
  • 1,225
  • 7
  • 9
  • Hi Philippe! Thanks for answer, but my question was: while doing unboxing when value copied and when not Thanks – zzfima Sep 19 '16 at 06:16
  • @zzfima The value is never copied **when** unboxing, but it is almost always copied **afterward**, when using the value. I don't know of any C# code that would compile to an `unbox` not followed by some kind of copying (even `unsafe` code with `&` operator), but you could certainly do it directly in IL. – Philippe Sep 19 '16 at 06:46
  • in my example "Console.WriteLine(v + ", " + (Int32)o)" Richter said, that when doing unboxing of "o" it is not copied, only pointer returns – zzfima Sep 19 '16 at 07:08
  • @zzfima Sure. And then the value inside the box for `o` is boxed again (thus copying it inside the new box) for the call to `String.Concat()`. That's why Richter said you may be surprised there are actually 3 `boxing`. There is not a first copy from the box to the stack, and then a second copy to the second box, only a copy from the first box directly to the second one. – Philippe Sep 19 '16 at 09:08