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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.