So I am new to C# and I am having difficulty understanding out
. As opposed to just returning something from a function
using System;
class Retur
When one variable is concerned out and return are OK. But what if you wanted to return more than 1 values? Out
helps in that.
static void CalculateArea(out double r, out double Foo)
{
//Can return 2 values in terms of out variables.
}
static double CalculateArea(double r)
{
// Will return only one value.
}
The out
keyword is mostly used when you want to return more than one value from a method, without having to wrap the values in an object.
An example is the Int32.TryParse
method, which has both a return value (a boolean representing the success of the attempt), and an out
parameter that gets the value if the parsing was successful.
The method could return an object that contained both the boolean and the integer, but that would need for the object to be created on the heap, reducing the performance of the method.
Only time I tend to use out
is when I need multiple things returned from a single method. Out
lets you avoid wrapping multiple objects into a class for return. Check out the example at the Microsoft Out page.
A good use of out
instead of return
for the result is the Try
pattern that you can see in certain APIs, for example Int32.TryParse(...)
. In this pattern, the return value is used to signal success or failure of the operation (as opposed to an exception), and the out
parameter is used to return the actual result.
One of the advantages with respect to Int32.Parse
is speed, since exceptions are avoided. Some benchmarks have been presented in this other question: Parsing Performance (If, TryParse, Try-Catch)
You can have multiple out parameters, so if you need to return multiple values, it's a bit easier than creating a special class for your return values.