SHARE:

Introducing C# 9: Extending Partial Methods

Introduction

C# 8 (and above) has some restrictions regarding partial methods. For example :

  • Partial methods must have a void return type
  • Partial methods can’t have out parameters
  • Partial methods can’t have any accessibility keyword (public, private, protected etc….)

C# 9 aims to remove these restrictions. If you want to learn more about the motivation behind this, you can find a good description on the Github page here: https://github.com/jaredpar/csharplang/blob/partial/proposals/extending-partial-methods.md

Behavior before C# 9

Below are some examples of what happens when a partial methods has or not an accessibility keyword, has or not an out parameter, a void or not return type, implements an interface:

Note for interface implementation: because C# 8 and above doesn’t support accessibility keyword on partial methods it’s impossible to implement partial method from its interface signature, because without any keyword, the method is implicitly a private method, which doesn’t allow to implement this method from its interface signature.

Behavior with C# 9

Now let’s take the exact same partial class definition above and see what’s the compiler behavior now:

C# 9 allows now what was missing in C# 8 and above, but, it requires now an implementation on methods that are defined with:

  • void or not return type
  • out parameters
  • accessibility keyword (public, private, protected etc….)

As you can see above C# 9 brings a new error code with its message if the previous conditions are not fulfilled:

CS8795: Partial method must have an implementation part because it has accessibility modifiers

I’m really excited by what’s coming with C# 9, and you ? 😉

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.
%d bloggers like this: