Because I am building the string in another function which can get fairly
large and I don't want to pass the actual string which will get very large.
A string is a reference type, so whenever you pass it, it doesn't get
copied on the stack anyway. You're always passing a reference.
The only question is whether you want to replace the string you passed
with a different string, in which case you need the "ref" keyword. What
"ref" says is that you may want to change the variable that contains a
reference (pointer) to the string to contain a reference (pointer) to a
different string upon return.
So, if HandleString changes the string to which theString points, and
wants the caller to FirstSub to receive the change, then you need
"ref". Something like this:
void FirstSub(ref string theString)
{
...
HandleString(ref theString);
...
}
void HandleString(ref string aString)
{
aString = String.Format(...);
}
Then any caller to FirstSub will get a changed string on return.
If FirstSub and HandleString are just _using_ the string for something,
but not replacing it with a different string, there is no reason to use
"ref".
I am curious as to why it works, however.
If I have testString and I pass it as a reference to FirstSub, then it has
the reference to testString (not the string itself). When I pass it to
HandleString, aren't I passing a reference to a reference of testString?
No, because C# isn't like C. In C#, when you mention the variable name
then the language dereferences automatically. So, in
void FirstSub(ref string theString)
{
...
}
when you say "theString", you are not talking about the reference to
"theString". You are talking about "theString" itself (which is a
reference to a string). So, no, you never get a reference to a
reference to a reference, because there is no language construct for
talking about "the reference to the reference called 'theString'". The
"ref" simply indicates how "theString" gets passed to the method. Once
inside the FirstSub method, "theString" is just a normal string again.