Methods and Parameters
Out Parameters
An out parameter lets a method return an extra value alongside a success flag.
out parameter
An out parameter is assigned inside the method before the method returns.
Out Parameters
OutParameters.cs
using System;
class Program
{
static bool TryDouble(int input, out int doubled)
{
if (input < 0)
{
doubled = 0;
return false;
}
doubled = input * 2;
return true;
}
static void Main()
{
int input = 4;
bool ok = TryDouble(input, out int doubled);
string status = ok ? "ok" : "invalid";
Console.WriteLine($"input={input}");
Console.WriteLine($"status={status}");
Console.WriteLine($"doubled={doubled}");
}
}
Follow the Out Value
inputstarts as4.TryDouble(input, out int doubled)passes4and asks the method to filldoubled.- Since
4is not negative, the method setsdoubledto8. - The method returns
true. - The caller turns
trueintostatus=ok. | input | method result | doubled | status | | --- | --- | --- | --- | | 4 | true | 8 | ok | | -1 | false | 0 | invalid | | 8 | true | 16 | ok |
Exercise: OutParameters.cs
Reproduce input=4, status=ok, and doubled=8, then use the pinned input variants -1 and 8 to predict status=invalid doubled=0 and status=ok doubled=16.