Skip to content

Partial events and constructors C# 14.0code generation

Allow constructors and events to be partially defined like partial methods and properties.

Partial methods C# 3.0 and partial properties C# 13.0 allow splitting a declaration and its implementation across files. This is especially useful for code generation scenarios where a generator provides the implementation.

C# 14 extends this to constructors and events, completing the set of members that can be partial.

Code

C#
// User-written file
partial class Customer
{
    public partial Customer(string name);
    public partial event EventHandler? NameChanged;
}

// Code-generated file
partial class Customer
{
    private string name;

    public partial Customer(string name)
    {
        this.name = name;
    }

    public partial event EventHandler? NameChanged
    {
        add => nameChangedHandlers += value;
        remove => nameChangedHandlers -= value;
    }
}
C#
// User-written file
partial class Customer
{
    partial void Initialize(string name);

    public Customer(string name)
    {
        Initialize(name);
    }
}

// Code-generated file
partial class Customer
{
    private string name;

    partial void Initialize(string name)
    {
        this.name = name;
    }
}

Notes

  • Only the implementing declaration of a partial constructor can include a constructor initializer (: this() or : base())
  • Only one partial type declaration can include primary constructor syntax
  • The implementing declaration of a partial event must include add and remove accessors

More information