C# out parameters vs returns

Frank Visaggio picture Frank Visaggio · Jun 26, 2012 · Viewed 8.5k times · Source

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?

Answer

Tudor picture Tudor · Jun 26, 2012

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)