It means you know what you're doing - that you're acknowledging it's an out
parameter. Do you really want the utterly different behaviour to happen silently? The same is true for ref
, by the way.
(You can also overload based on by-value vs out/ref, but I wouldn't recommend it.)
Basically, if you've got an (uncaptured) local variable and you use it as a non-out/ref argument, you know that the value of that variable won't be changed within the method. (If it's a reference type variable then the data within the object it refers to may be changed, but that's very different.)
This avoids the kind of situation you get in C++ where you unknowingly pass something by reference, but assume that the value hasn't changed...
You should use out
unless you need ref
.
It makes a big difference when the data needs to be marshalled e.g. to another process, which can be costly. So you want to avoid marshalling the initial value when the method doesn't make use of it.
Beyond that, it also shows the reader of the declaration or the call whether the initial value is relevant (and potentially preserved), or thrown away.
As a minor difference, an out parameter needs not be initialized.
Example for out
:
string a, b;
person.GetBothNames(out a, out b);
where GetBothNames is a method to retrieve two values atomically, the method won't change behavior whatever a and b are. If the call goes to a server in Hawaii, copying the initial values from here to Hawaii is a waste of bandwidth. A similar snippet using ref:
string a = String.Empty, b = String.Empty;
person.GetBothNames(ref a, ref b);
could confuse readers, because it looks like the initial values of a and b are relevant (though the method name would indicate they are not).
Example for ref
:
string name = textbox.Text;
bool didModify = validator.SuggestValidName(ref name);
Here the initial value is relevant to the method.
Best Answer
ref
tells the compiler that the object is initialized before entering the function, whileout
tells the compiler that the object will be initialized inside the function.So while
ref
is two-ways,out
is out-only.