C# 9 new features for methods and functions

This is the third article in our C# 9 series. In the previous articles, we covered top-level programs and target-typed expressions and new features for pattern matching. In this article, we’ll look at new features for methods, anonymous functions, and local functions.

Covariant return types

When overriding base class members or implementing interfaces, C# 9 allows you to use a more specific return type:

class Person
{
 public virtual Person Clone() { ... }
}
 
class Student : Person
{
 public override Student Clone() { ... }
}

In previous versions of C#, the return type had to match the base declaration. A cast was required in order to obtain the actual more specific type:

Student clone = (Student)student.Clone();

Static anonymous functions

For a long time, C# has supported the declaration of anonymous functions using anonymous methods or lambda expressions:

// Anonymous functions:
// - C# 2.0: anonymous methods
Func<string, int> = delegate(string arg) { return arg.Length; };
// - C# 3.0: lambda expressions
Func<string, int> = arg => arg.Length;

Anonymous functions can use local variables. To disallow this, and require explicit passing of all arguments, we can now mark anonymous functions as static:

// error CS8820: static anonymous function references ‘offset’
int offset = 20;
Func<string, int> d1 = static delegate(string arg) { return arg.Length + offset; };
Func<string, int> d2 = static arg => arg.Length + offset;

Attributes on local functions

C# 7 introduced local functions, which are defined in the calling method. C# 8 enhanced these local functions and permitted them to be marked as static to disallow the use of local variables (similar to the previous section).

C# 9 makes it possible to add attributes to local functions. The following example applies the DllImport attribute to a local function:

public static void Terminate(this Process p)
{
   const int SIGTERM = 15;
   kill(p.Id, SIGTERM);
 
   [DllImport("libc", SetLastError = true)]
   static extern int kill(int pid, int sig);
}

Extended partial methods

To facilitate customizing generated code, C# 3 introduced the concept of partial methods.

The generated C# code includes a method marked with partial with no body. The body for the method is provided by the user in a separate file.

C# 3 doesn’t require the user to provide a body. When the code is compiled, the compiler uses the method that was provided by the user, or omits the calls if there is no such method.

Because providing the implementation is optional, partial methods are not allowed to have output parameters or non-void return types:

// -- MyForm.generated.cs --
public partial class MyForm : Form
{
   public MyForm()
   {
   	// ...
   	// generated code to initialize components.
   	// ...
 
   	OnComponentsInitialized();
   }
 
   partial void OnComponentsInitialized();
}
 
// -- MyForm.cs --
public partial class MyForm
{
   partial void OnComponentsInitialized()
   {
   	// user code
   }
}

C# 9 allows partial methods to have a return type and output parameters. The compiler requires there to be an implementation. This extended kind of partial method must have an accessibility modifier, which is no longer limited to private scope.

This lets the user split the declaration of a method (the method signature) from its definition (the code).

Extended partial methods go hand-in-hand with another new C# compiler feature: source generators. A source generator is code that runs during compilation to produce additional source code that gets compiled. You can learn more about source generators in Introducing C# Source Generators.

As you probably guessed, a source generator is responsible for generating the implementation of partial methods. The following example shows a partial method that can cause a source generator to emit an implementation that is optimized for the regular expression provided in the RegexGenerated attribute:

[RegexGenerated("(dog|cat|fish)")]
public partial bool IsPetMatch(string input);

Conclusion

This article covered new capabilities for methods and functions in C# 9. We learned that overridden methods can now return more specific types, anonymous methods can be marked static to require passing in all parameters, and local functions can now have attributes. Finally, we looked at extended partial methods and how they are used with C# source generators.

In the next article, we'll look at init accessors and records.

C# 9 can be used with the .NET 5 SDK, which is available on Red Hat Enterprise Linux and Red Hat OpenShift, on Fedora, and from Microsoft for Windows, macOS, and other Linux distributions.

Last updated: April 21, 2021

Comments