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
