Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use in vs ref vs out

Tags:

c#

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?

like image 898
Dale Avatar asked Oct 04 '09 17:10

Dale


People also ask

What is the difference between in ref and out keywords?

ref keyword is used when a called method has to update the passed parameter. out keyword is used when a called method has to update multiple parameter passed. ref keyword is used to pass data in bi-directional way. out keyword is used to get data in uni-directional way.

When should you use ref in C#?

The ref keyword in C# is used for passing or returning references of values to or from Methods. Basically, it means that any change made to a value that is passed by reference will reflect this change since you are modifying the value at the address and not just the value.

What is the difference between reference parameters and output parameters when should you use each?

The reference parameters are used to pass parameters to the method by reference. The output parameters are used to pass the result back from the method. In C#, out keyword is used for output parameters and ref keyword is used to reference parameters.


1 Answers

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.

like image 97
peterchen Avatar answered Sep 18 '22 15:09

peterchen