When to use "out" instead of "ref"
When choosing between "out" and "ref" parameters, the default selection is "out" unless "ref" is specifically required.
The difference between Out and Ref
"ref" allows a method to modify the original value of a variable passed as a parameter, while "out" prohibits this ability. This distinction becomes critical when it comes to data transfer across processes or machines, as marshalling initial values can lead to unnecessary processing.
Suitable scenarios for using “out”
Consider the following scenario:
<code class="language-c#">person.GetBothNames(out a, out b);</code>
Assuming "person" is an object and "GetBothNames" is a method that retrieves two values, the initial values of "a" and "b" have nothing to do with the operation of the method. In this case, using "in" or "out" is a matter of preference, with "out" being the recommended choice to eliminate useless marshalling of initial values.
Scenarios suitable for using "ref"
On the other hand, "ref" is appropriate when modifying the initial value is part of the method's intent:
<code class="language-c#">bool didModify = validator.SuggestValidName(ref name);</code>
The "name" parameter is passed by reference, allowing the "validator" method to change its value and return "didModify" to indicate the change.
In short, in most cases, "out" is a better choice if the initial variable value does not need to be modified, while "ref" becomes necessary when such modifications are required.
The above is the detailed content of Out vs. Ref Parameters in C#: When Should You Use Which?. For more information, please follow other related articles on the PHP Chinese website!