11

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?

Matt Ellen
  • 11,268
  • 4
  • 68
  • 90
Frank Visaggio
  • 3,642
  • 9
  • 34
  • 71
  • 8
    Study `Dictionary.TryGetValue` and `int.TryParse` and see if those examples explain the utility of `out`. – Kirk Woll Jun 26 '12 at 17:25
  • 3
    `out` is mostly used when you need to return multiple, unrelated values from a method. As well, it is often used to simulate pointers when interoping with native code via COM or p/invoke. – dlev Jun 26 '12 at 17:26
  • 1
    Remember in C/C++ we have pointers. When you passed a pointer into a function you could modify it within the function and the value would change in the calling function as well. out does pretty much the same thing. – carny666 Jun 26 '12 at 18:16
  • 1
    @carny666: I think `ref` is more similar to C++ references than `out`. – Tudor Jun 26 '12 at 18:55
  • @KirkWoll those were two excellent examples thanks! – Frank Visaggio Jun 26 '12 at 19:11
  • possible duplicate of [Which is better, return value or out parameter?](http://stackoverflow.com/questions/810797/which-is-better-return-value-or-out-parameter) – nawfal Jan 15 '14 at 05:06

5 Answers5

16

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)

Community
  • 1
  • 1
Tudor
  • 61,523
  • 12
  • 102
  • 142
8

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.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • I'm wondering also about the performance difference (if any). Coming from a c++ environment the argument is that copying an object when returned by value is more expensive. Is this also true for C#? I mean if you construct a brand new massive object within the function and return it, will it get copied to whatever you are assigning to? As opposed to creating the object and changing it via the out keyword? Or is this irrelevant in C#? – Reasurria May 21 '15 at 13:18
  • @Reasurria: If you create an object and return it, it's only the reference that is returned, the objects is not cloned. In .NET objects are only cloned if you specifically clone them, passing objects around doesn't create new copies. – Guffa May 21 '15 at 14:38
4

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.

Coeffect
  • 8,772
  • 2
  • 27
  • 42
  • Note that in recent versions of C# you can now do this with value tuples. Eg (string name, int age) GetMultipleValues() { return ("james", 31); } – Damien Sawyer Jul 20 '18 at 16:51
2

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.

Rob H
  • 1,840
  • 16
  • 25
1

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.
}
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208