Should the argument be passed by reference in this .net example?
Posted
by Hamish Grubijan
on Stack Overflow
See other posts from Stack Overflow
or by Hamish Grubijan
Published on 2010-05-20T18:30:02Z
Indexed on
2010/05/20
18:40 UTC
Read the original article
Hit count: 167
c#
|pass-by-reference
I have used Java, C++, .Net. (in that order). When asked about by-value vs. by-ref on interviews, I have always done well on that question ... perhaps because nobody went in-depth on it. Now I know that I do not see the whole picture.
I was looking at this section of code written by someone else:
XmlDocument doc = new XmlDocument();
AppendX(doc); // Real name of the function is different
AppendY(doc); // ditto
When I saw this code, I thought: wait a minute, should not I use a ref
in front of doc
variable (and modify AppendX/Y
accordingly? it works as written, but made me question whether I actually understand the ref
keyword in C#.
As I thought about this more, I recalled early Java days (college intro language). A friend of mine looked at some code I have written and he had a mental block - he kept asking me which things are passed in by reference and when by value. My ignorant response was something like: Dude, there is only one kind of arg passing in Java and I forgot which one it is :). Chill, do not over-think and just code.
Java still does not have a ref
does it? Yet, Java hackers seem to be productive. Anyhow, coding in C++ exposed me to this whole by reference business, and now I am confused.
Should ref
be used in the example above?
I am guessing that when ref
is applied to value types: primitives, enums, structures (is there anything else in this list?) it makes a big difference. And ... when applied to objects it does not because it is all by reference. If things were so simple, then why would not the compiler restrict the usage of ref
keyword to a subset of types.
When it comes to objects, does ref
serve as a comment sort of? Well, I do remember that there can be problems with null
and ref
is also useful for initializing multiple elements within a method (since you cannot return multiple things with the same easy as you would do in Python).
Thanks.
© Stack Overflow or respective owner