principlecsharpCritical
When to use in vs ref vs out
Viewed 0 times
refusewhenout
Problem
Someone asked me the other day when they should use the parameter keyword
Since
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?Solution
You should use
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
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:
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
Here the initial value is relevant to the method.
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.
Code Snippets
string a, b;
person.GetBothNames(out a, out b);string a = String.Empty, b = String.Empty;
person.GetBothNames(ref a, ref b);string name = textbox.Text;
bool didModify = validator.SuggestValidName(ref name);Context
Stack Overflow Q#1516876, score: 418
Revisions (0)
No revisions yet.