Output Parameters

Closely related to reference parameters are output parameters. Conceptually, they serve as additions to the single “return channel” provided by a method’s return type. By using the out modifier, you can create such a method:

static bool TrySqrt(int input, out double root){    root = 0.0;  // Will learn a in while why this is needed    if (input < 0)        return false;    root = Math.Sqrt(input);    return true;}

In this example, we use the return type to denote success or failure, while the output parameter will receive the result in case of success. This is a common pattern for various Base Class Library (BCL) types such as numeric value types that have a TryParse method:

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.