C# out parameters vs returns

折月煮酒 提交于 2019-12-01 03:29:11
Tudor

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)

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.

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.

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.
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!