3

I was reading about passing by reference in C# and while doing that I read the following sentence which confuses me.

"There is no boxing of a value type when it is passed by reference."

Though I know what boxing is, I think I miss the actual depth of information containted in this sentence. I know that it basically says no boxing occurs and of course neither does unboxing but what other conclusions could I draw from this? Is passing by value/reference anyhow related to boxing/unboxing?

Community
  • 1
  • 1
D3v
  • 305
  • 1
  • 2
  • 16
  • 2
    Boxing is not related to passing values types by reference and that for good because boxing is slow. I guess author of the book wanted to show difference between passing reference type by value (when you have reference you can change object properties but not reference itself) and passing value types by ref (behaviour will be similar to passing reference types but you get not slow boxing) – csharpfolk Nov 17 '16 at 20:56
  • 2
    I don't agree that this is a duplicate question. They're talking about the same thing, but there's no answer given on the dup that addresses the OP's question. Voting to reopen. – itsme86 Nov 17 '16 at 20:56
  • 1
    [This answer](http://stackoverflow.com/a/4807391/1141432) more directly relates to the OP's question. – itsme86 Nov 17 '16 at 20:59
  • 2
    The rest of the quote from the article linked is, "Do not confuse the concept of passing by reference with the concept of reference types. The two concepts are not the same. A method parameter can be modified by `ref` regardless of whether it is a value type or a reference type. There is no boxing of a value type when it is passed by reference." With that in mind, I think the article author was just trying to say that "pass by reference" doesn't make a value type a "reference type", i.e. it doesn't box the value type (boxing stores a value type in an `object`, which is a reference type). – wablab Nov 17 '16 at 21:00
  • I've read the posts mentioned it the comments or referred to as identical to my question. Still instead of beating around the bush I would like to address the point directly about whether there is any kind of relation between passing parameters and boxing/unboxing even if it is in some specific case. – D3v Nov 17 '16 at 21:04
  • 2
    No they aren't related, boxing is required when a value type needs to be treated as a reference type. Passing by reference is used to alias locations within method calls. – Lee Nov 17 '16 at 21:15

1 Answers1

1

If you are passing value types by reference there is no boxing and unboxing involved. There is memory aliasing, as is told in c# in nutshell book. You can even try it in Linqpad. After displaying it in IL code you will see there is no boxing/unboxing involved.

Jan Válek
  • 424
  • 4
  • 14