When should we use an out
parameter in C#?
For example
bool TryGetValue(out object value);
vs.
class ReturnType
{
public bool Found {get;set;}
public object Value {get;set;}
}
ReturnType TryGetValue();
Apart from reducing the number of lines of code, when should an out
parameter to be used and when it should be returned as return type?
The out is a keyword in C# which is used for the passing the arguments to methods as a reference type. It is generally used when a method returns multiple values.
Generally speaking, out parameters must be initialized before the called method returns control to the caller.
Out is used where your method needs to return multiple values. If you use return, then the data is first written to the methods stack and then in the calling method's. While in case of out, it is directly written to the calling methods stack.
Variables passed as out arguments do not have to be initialized before being passed in a method call. However, the called method is required to assign a value before the method returns.
Out can also be used for operations that might fail (typically found in methods starting Try*).
E.g. TryParse will return a bool indicating success/failure while using the out value as the result. This avoids having to throw exceptions.
If there's no general reason to encapsulate the multiple values together, other than for this call, then creating a separate type is probably over the top.
On the other hand, if you have multiple out parameters and a return value which all logically belong together (e.g. first name, last name, telephone number) then it would probably make sense to create an appropriate type (e.g. "Contact") and return that.
One alternative for the TryGetValue
option is to use nullable value types, if the value in question is a value type. For instance, int.TryParse could have had a signature of:
int? TryParse(string text)
(with an overload taking an IFormatProvider
of course).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With