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

  1. input starts as 4.
  2. TryDouble(input, out int doubled) passes 4 and asks the method to fill doubled.
  3. Since 4 is not negative, the method sets doubled to 8.
  4. The method returns true.
  5. The caller turns true into status=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.