Difference between pass-by-value and pass-by-reference
A MS help page about the difference between pass-by-value and pass-by-reference seems quite clear to me:
http://msdn.microsoft.com/en-us/library/8b0bdca4.aspx
However, a user comment at the end has confused me somewhat. It says (among other things) this:
if you don‘t use the ref or out keywords, then arguments to methods are passed by value.
The comment seems quite wrong to me. Is it?
(I posted part of the comment out of context: Here's the full comment:)
The text says: "... but when a class instance is passed, a reference is passed. ..." This is incorrect, as you can see in:
C# Language spe开发者_Go百科cification Version 4.0 (a Microsoft free download) 5.1.4 Value parameters A parameter declared without a ref or out modifier is a value parameter.
So, in the example above, the class instance is passed by value, and not by reference.
It is the full comment which is really confusing me... The class instance is passed by value and not by reference? Does that not imply that the instance bytes are pushed onto the stack?
The comment is true. Without ref
or out
, the variable is passed by value. However, with objects, what you are passing by value is a reference.
The only time you would want to pass an object-reference by reference is if you are assigning a new object to the parameter within the method and you want that reassignment to affect the caller's copy of the reference.
You aren't ever really passing an object around. Instead you are passing around references to an object. With that in mind, this byval/byref business applies to the object-reference, not the object itself.
Jon Skeet has a great post about this topic.
The complete comment is misleading. The object's reference is passed by value.
The comment is completely correct. The confusion here is that value types and reference types are pretty much unrelated to passing an argument by value or by reference.
When you pass a value type as a non-ref parameter, you pass its value. That's clear enough. For a reference type, though, you are still only passing a value: You are passing the value of the reference itself.
If the parameter is ref/out
, though, then you are actually saying that the parameter is an alias for the variable that is actually being passed in. In that case, it doesn't matter if it's a value type or a reference type; a reference to the variable is being passed, not just a value.
精彩评论