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
C#
Console.WriteLine(customer.GetFullName()); // Extension method
Console.WriteLine(customer.FullName); // Extension property
static class CustomerExtensions
{
extension(Customer c)
{
public string GetFullName() => c.FirstName + " " + c.LastName;
public string FullName => c.FirstName + " " + c.LastName;
}
}C#
Console.WriteLine(customer.GetFullName()); // Extension method (but no extension properties)
static class CustomerExtensions
{
public static string GetFullName(this Customer c) => c.FirstName + " " + c.LastName;
// Extension properties were not possible
// Had to use a static helper method instead
public static string GetFullName2(this Customer c) => c.FirstName + " " + c.LastName;
}Notes
- Replaces the old convention of using
thison 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