Skip to content

Extending partial methods C# 9.0code generation

Partial methods can have return values and out parameters.

Partial methods allow generated code to offer hooks for user-written code to be called at the appropriate time.

Calls to partial methods were removed by the compiler when the user chose not to provide an implementation. Because of this they were not permitted to pass back values either by return values or via out parameters.

Extended partial methods remove these limitations in exchange for requiring the user to provide an implementation and specifying explicit accessibility e.g public, private.

Code

C#
string PrepareLabel(Address address)
{
    return FormatAddress(address) ?? address.ToString();
}

partial string FormatAddress(Address address);
C#
string PrepareLabel(Address address)
{
    var defaultLabel = address.ToString();
    var labelList = new List<string>(defaultLabel.Split('\n'));
    FormatAddress(address, labelList);
    return String.Join('\n', labelList);
}

// To manipulate data you must do it in a mutable data structure like List
partial void FormatAddress(Address address, List<string> formattedResult);

More information