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, such a method can be created:
static bool TrySqrt(int input, out double root){ root = 0.0; // Will learn 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:
Console.Write("Enter your age: ");string input = Console.ReadLine(); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access