Ix_PAUL_xI (2) [Avatar] Offline
#1
Hi,

I have a question regarding the section of the book regarding myth 3 in the displeeing myths section of value and reference types. I understand what you are saying in the book and also the example given. However, when I look at example 4 (passing reference type by value) at the following link http://msdn.microsoft.com/en-us/library/0f66670z(VS.71).aspx I am getting confused. Is this not doing the opposite of what you are saying in the book?

Thanks,
Paul
mgravell (64) [Avatar] Offline
#2
Re: MYTH #3: “OBJECTS ARE PASSED BY REFERENCE IN C# BY DEFAULT”
Apols for jumping in...

They are saying exactly the same thing; changes to the variable (the reference) are not reflected back to the caller - this is the line marked "This change is local.". Inside "Change" we could set "arr" to null, to a new array, etc - but "Main" will never know we did it.

However, changing properties etc of the object [reference type] *are* reflected - this includes changing elements of arrays (marked "This change affects the original element") - because at this point we have two variables (references) pointing to the same actual array (instance).
jon.skeet (448) [Avatar] Offline
#3
Re: MYTH #3: “OBJECTS ARE PASSED BY REFERENCE IN C# BY DEFAULT”
Exactly what Marc said, basically smilie
mgravell (64) [Avatar] Offline
#4
Re: MYTH #3: “OBJECTS ARE PASSED BY REFERENCE IN C# BY DEFAULT”
Except the book says it more clearly.
Ix_PAUL_xI (2) [Avatar] Offline
#5
Re: MYTH #3: “OBJECTS ARE PASSED BY REFERENCE IN C# BY DEFAULT”
Ok, thanks for the replies guys, I think I am with you.

Just to clarify - if we make a change to the original reference the change is reflected back. If we create a new reference the change isn't reflected back, which is contrary to the myth?
jon.skeet (448) [Avatar] Offline
#6
Re: MYTH #3: “OBJECTS ARE PASSED BY REFERENCE IN C# BY DEFAULT”
Sort of - except you can't actually make a change to a reference - but you can make a change to an object.

There's more about this on my web site:
http://pobox.com/~skeet/csharp/parameters.html

Basically the myth is just playing fast and loose with the term "pass by reference" (and getting confused about what's actually passed in the first place). This doesn't bother too many people, but it confuses the heck out of people who know what it really means!

Message was edited by:
jon.skeet