Press "Enter" to skip to content

Updates to Extensions in C# 14

The word miners in the NDepend blogging mines clue us in on an update to the C# language:

A few remarks:

  • If the extension is generic, the type parameter (if any) is specified immediately after the extension keyword.
  • The receiver ReadOnlySpan<T> span applies to one or more extension methods (or members) declared within the same extension block. This logical grouping is a core advantage of the new syntax, improving clarity and structure when extending a type.
  • As far as the C# compiler is concerned, the two methods Truncate() are strictly equivalent. Therefore, one must be commented out for the program to compile.
  • Notice the call to AsSpan() in the first line. Extension methods require the receiver type to match exactly ReadOnlySpan<T>, hence it doesn’t apply to string unless you explicitly cast. This is not specific to the new syntax but worth mentioning.

Read on for examples of how extension methods and extension members will open up opportunities to improve existing C# code.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.