Skip to content

Extension members C# 14.0discovery

Add properties to existing classes just like extension methods.

Extension methods C# 3.0 allowed you to decorate existing classes with additional instance methods.

C# 14 brings a new syntax that also allows for extension properties and methods as well as static properties and methods using the new extension keyword.

Code

csharp
Console.WriteLine(customer.GetFullName()); // Extension method
Console.WriteLine(customer.FullName);      // Extension property
Console.WriteLine(Customer.Empty);         // Static extension property

static class CustomerExtensions
{
    extension(Customer c)
    {
        public string GetFullName() => c.FirstName + " " + c.LastName;

        public string FullName => c.FirstName + " " + c.LastName;
    }

    extension(Customer)
    {
        public static Customer Empty => new Customer { FirstName = "", LastName = "" };
    }
}
csharp
Console.WriteLine(customer.GetFullName()); // Extension method (the only option)

static class CustomerExtensions
{
    public static string GetFullName(this Customer c) => c.FirstName + " " + c.LastName;

    // Extension properties were not possible — callers had to invoke a method
    // even when no arguments were required.
    // Static extension members on the type itself were also not possible —
    // there was no way to add Customer.Empty without modifying Customer.
}

Notes

  • Replaces the old convention of using this on the first parameter of a static method to declare extension methods
  • Extension properties were one of the most requested C# features on the dotnet/csharplang repository
  • Static extension members use extension(Type) without a parameter name

More information