A bit of history

Partial methods have been around for quite a long time in the C# language. They are super useful to extend auto-generated code by third-party libraries. Unfortunately, they also come with annoying limitations.

See also the original partial methods specification

C# 9.0 to the rescue

It seems there's a recurring theme in all the new features introduced in C# 9.0; Simplicity. Every new addition to the language tends towards reducing friction and make code easier to read. The idea to extend partial methods is no exception and removes all previous restrictions:

  1. Must have a void return type
  2. Cannot have out parameters
  3. Cannot have any accessibility (implicitly private)

Removing these limitations was necessary to enable the new C# code generators.

partial class Parser
    internal partial bool TryParse(string s, out int i);

partial class Parser
    internal partial bool TryParse(string s, out int i)
        i = 0;
        return true;

This example combines all the pre-C# 9.0 restrictions and demonstrates how these new capabilities can be useful.

  • The return type is bool
  • The method contains an out parameter (out int i)
  • The accessibility is internal

Still some restrictions

All of this is great but lifting these restrictions opens the door to other edge cases that need to be handled. That's why some new limits had to be added:

  • partial declarations with explicit accessibility must have a definition
  • partial declarations and definition signatures must match on all methods and parameter modifiers. The only aspects which can differ are parameter names and attribute lists (this is not new but rather an existing requirement of partial methods).

Hopefully, these new limitations won't be in your way and will just make sure you don't do something that will result in undefined behavior or, even worst, a runtime error.

If you are interested to learn more about C# 9.0, take a look at the code samples I built on GitHub. Also, don't forget first to read my post on how to enable C# 9.0 as it's still in preview.