ดาว ดาว - 3 months ago 10
C# Question

When to use ref vs out

Someone asked me the other day when they should use the parameter keyword

out
instead of
ref
. While I (I think) understand the difference between the
ref
and
out
keywords (that has been asked before) and the best explanation seems to be that
ref
==
in
and
out
, what are some (hypothetical or code) examples where I should always use
out
and not
ref
.

Since
ref
is more general, why do you ever want to use
out
? Is it just syntactic sugar?

Answer

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.