Sunday, May 13, 2012

All about "out" and "ref"


5down vote



[ref] and [out] both allow the called method to modify a parameter. The difference between them is what happens before you make the call.

[ref] means that the parameter has a value on it before going into the function. The called function can read and or change the value any time. The parameter goes in, then comes out


[out] means that the parameter has no official value before going into the function. The called function must initialize it. The parameter only goes out


Here's my favorite way to look at it: [ref] is to pass variables by reference. [out] is to declare a secondary return value for the function. It's like if you could write this:
// This is not C#
public (bool, string) GetWebThing(string name, [ref] Buffer paramBuffer);

// This is C#
public bool GetWebThing(string name, [ref] Buffer paramBuffer, [out] string actualUrl);

Here's a more detailed list of the effects of each alternative:

Before calling the method:

[ref]: The called must set the value of the parameter before passing it to the called method.

[out]: The caller method is not required to set the value of the argument before calling the method. Most likely, you shouldn't. In fact, any current value is discarded.

During the call:

[ref]: The called method can read the argument at any time.

[out]: The called method must initialize the parameter before reading it.

Remoted calls:

[ref]: The current value is marshalled to the remote call. Extra performance cost.

[out]: Nothing is passed to the remote call. Faster.

Technically speaking, you could use always [ref] in place of [out], but [out] allows you to be more precise about the meaning of the argument, and sometimes it can be a lot more efficient.

No comments: