liveBook · Manning

Output parameter

As explained in .NET in Action, Second Edition

An out parameter is a C# method parameter that the method must assign before returning and that provides an additional output value to the caller.

An out parameter gives a method an additional value to return. The method must assign it before returning, and the caller must provide a place to store it. Paired with a Boolean return, it can provide a result on success and signal failure without an exception. section 3.1.2

An ASCII-art renderer uses this pattern to return rendered text while reporting whether a requested font was found. An ASP.NET Core endpoint uses the Boolean result to return content or a 404 response. section 3.1.2

Listing 3.15 Modifying Write method to indicate whether font was found
public static class AsciiArt
{
  public static bool Write(string text,       #1
    out string? asciiText,                    #2
    string? fontName = null)
  {
    FiggleFont? font = null;
    if (!string.IsNullOrWhiteSpace(fontName))
    {
      font = typeof(FiggleFonts)
        .GetProperty(fontName,
          BindingFlags.Static | BindingFlags.Public)
        ?.GetValue(null)
        as FiggleFont;
    }
    else
    {
      font = FiggleFonts.Standard;            #3
    }
 
    if (font == null)                         #4
    {
      asciiText = null;                       #5
      return false;                           #6
    }
  
    asciiText = font.Render(text);            #7
    return true;
  }
}

The implementation assigns the out value on both paths: null when the font is missing, and rendered text when it is found. section 3.1.2

How .NET in Action, Second Edition covers it

How deep it goes
Defines assignment and caller requirements, then demonstrates a success-or-failure implementation; it does not explore broader language internals.
Examples
Demonstrates an ASCII-art renderer that returns rendered text or reports an invalid font.
What you can do after
Apply C# out parameters in an ASP.NET Core endpoint to return content on success and 404 on failure.
How it connects
Connects out parameters to Boolean return values, exceptions, and ASP.NET Core action results.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.