adsense

Friday, July 11, 2025

C# 14 Extension members

 C# 14 introduces new syntax for defining extension members, expanding on traditional extension methods. Key additions include:

  • Extension properties and indexers alongside extension methods.

  • Ability to define static extension members, making them appear as if they are static members of the extended type


Two Types of Extension Blocks:
Instance-like extension members (e.g., sequence.IsEmpty):
 
extension<TSource>(IEnumerable<TSource> source)
{
    public bool IsEmpty => !source.Any();
    public TSource this[int index] => source.Skip(index).First();
    public IEnumerable<TSource> Where(Func<TSource, bool> predicate) { ... }
}

Static-like extension members (e.g., IEnumerable<int>.Identity):
 
extension<TSource>(IEnumerable<TSource>)
{
    public static IEnumerable<TSource> Combine(IEnumerable<TSource> first, IEnumerable<TSource> second) { ... }
    public static IEnumerable<TSource> Identity => Enumerable.Empty<TSource>();
}
These features allow more natural syntax and better integration with existing types by simulating both instance and static members via extensions.

Cheers
Samitha