Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 views
in Technique[技术] by (71.8m points)

reference - C# out parameters vs returns

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...