Reputation: 3712
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 ReturnTest
{
static double CalculateArea()
{
double r=5;
double area = r * r * Math.PI;
return area;
}
static void Main()
{
double output = CalculateArea();
Console.WriteLine("The area is {0:0.00}", output);
}
}
compare to this
using System;
class ReturnTest
{
static void CalculateArea(out double r)
{
r=5;
r= r * r * Math.PI;
}
static void Main()
{
double radius;
CalculateArea(out radius);
Console.WriteLine("The area is {0:0.00}",radius );
Console.ReadLine();
}
}
The first one is how I would generally do it. Is there a reason why I may want to use out
instead of just a return statement? I understand that ref
allows for 2 way communication, and that I generally shouldn't use ref
unless the function is doing something with the variable I am sending it.
However is there a difference between out and return statements, like shown above? Syntax-wise is there a reason to favor one or the other?
Upvotes: 12
Views: 10514
Reputation: 62479
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)
Upvotes: 18
Reputation: 700910
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.
Upvotes: 8
Reputation: 8866
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.
Upvotes: 4
Reputation: 1849
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.
Upvotes: 2
Reputation: 48600
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.
}
Upvotes: 1