Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should an `out` parameter be used instead of returning a complex type?

Tags:

c#

.net

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?

like image 485
Ramesh Avatar asked Apr 19 '09 16:04

Ramesh


People also ask

When should I use an out parameter in C#?

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.

Should we initialize an out parameter before a method returns?

Generally speaking, out parameters must be initialized before the called method returns control to the caller.

What is the difference between return value and out parameter sometime multiple value will be correct answers?

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.

Do you need to declare an out variable before you use it?

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.


2 Answers

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.

like image 199
Mark Simpson Avatar answered Nov 14 '22 22:11

Mark Simpson


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).

like image 43
Jon Skeet Avatar answered Nov 14 '22 22:11

Jon Skeet