New C# 12 preview features

Kathleen Dollard

Visual Studio 17.7 Preview 3 and .NET 8 Preview 6 continue the evolution of C# 12. This preview includes features designed to lay the groundwork for future performance enhancements. Easy access to inline arrays will allow libraries to use them in more places without effort on your part. This preview debuts an experimental feature called interceptors that allow generators to reroute code, such as to provide context specific optimization. Finally, nameof is enhanced to work in more places.

You can get C# 12 by installing the latest Visual Studio preview or the latest version of the .NET SDK. To check out C# 12 features, you’ll need to set the language version of your project to preview:

<PropertyGroup>
   <LangVersion>preview</LangVersion>
</PropertyGroup>

Since they are experimental, interceptors require an additional flag in your project file.

nameof accessing instance members

The nameof keyword now works with member names, including initializers, on static members, and in attributes:

internal class NameOf
{
    public string S { get; } = "";
    public static int StaticField;
    public string NameOfLength { get; } = nameof(S.Length);
    public static void NameOfExamples()
    {
        Console.WriteLine(nameof(S.Length));
        Console.WriteLine(nameof(StaticField.MinValue));
    }
    [Description($"String {nameof(S.Length)}")]
    public int StringLength(string s)
    { return s.Length; }
}

You can learn more at What’s new in C# 12.

Inline arrays

The InlineArrayAttribute was introduced to the runtime in a previous .NET 8 preview. This is an advanced feature that will be used primarily by the compiler, .NET libraries and some other libraries. The attribute identifies a type that can be treated as a contiguous sequence of primitives for efficient, type-safe, overrun-safe indexable/sliceable inline data. The .NET libraries improve performance of your application and tools using inline arrays.

The compiler creates different IL to access inline arrays. This results in a few restrictions, such as list patterns not being supported. In most cases, you access inline arrays the same as other arrays. The different IL creates performance gains without changing your code:

private static void InlineArrayAccess(Buffer10<int> inlineArray)
{
    for (int i = 0; i < 10; i++)
    {
        inlineArray[i] = i * i;
    }
    foreach (int i in inlineArray)
    {
        Console.WriteLine(i);
    }
}

Most folks will consume inline arrays, rather than create them. But, it’s nice to understand how things work. Inline arrays are fast because they rely on an exact layout of a specified length. An inline array is a type with a single field and marked with the InlineArrayAttribute that specifies the length of the array. In the type used in the previous example, the runtime creates storage for exactly ten elements in Buffer10<T> due to the attribute parameter:

[System.Runtime.CompilerServices.InlineArray(10)]
public struct Buffer10<T>
{
    private T _element0;
}

You can learn more at What’s new in C# 12.

Interceptors

This preview introduces an experimental feature called interceptors. It’s intended for advanced scenarios, particularly allowing better ahead of time compilation (AOT). As an experimental part of .NET 8, it may be changed or removed in a future version. Thus, it should not be used in production.

Interceptors allow specific method calls to be rerouted to different code. Attributes specify the actual source code location so interceptors are generally appropriate only for source generators. You can read the interceptors proposal to learn more about how interceptors work.

Because interceptors are an experimental feature, you’ll need to explicitly enable them in your project file:

<PropertyGroup>
   <Features>InterceptorsPreview</Features>
</PropertyGroup>

Interceptors enable exciting code patterns. A few examples are:

  • Calls that are known at compile time, like Regex.IsMatch(@"a+b+") with a constant pattern can be intercepted to use statically-generated code for optimization that is friendly to AOT.
  • ASP.NET Minimal API calls like app.MapGet("/products", handler: (int? page, int? pageLength, MyDb db) => { ... }) can be intercepted to register a statically-generated thunk which calls the user’s handler directly, skipping an allocation and indirection.
  • In vectorization, where foreach loops contain calls to user methods, the compiler can rewrite code to check for and use relevant intrinsics at runtime, but fall back to the original code if those intrinsics aren’t available.
  • Static dependency graph resolution for dependency injection, where provider.Register<MyService>() can be intercepted.
  • Calls to query providers could be intercepted to offer translation to another language (e.g. SQL) at compile time, rather than evaluating expression trees to translate at runtime.
  • Serializers could generate type specific (de)serialization based on the concrete type of calls like Serialize<MyType>(), all at compile time.

Most programmers will not use interceptors directly, but we hope they will play a significant role in our journey to make your applications run faster and be easier to deploy. Interceptors are expected to remain experimental in the C# 12/.NET 8 release and may be included in a future version of C#.

Summary

You can find more information about all of the features introduced so far at the What’s new in C# 12 page of Microsoft Learn and track the evolution of C# 12 features at the Roslyn Feature Status page.

You can check out the latest C# 12 features by downloading the latest Visual Studio preview or the latest version of the .NET SDK, and setting LangVersion to preview in your project file.

Let us know what you think!

34 comments

Discussion is closed. Login to edit/delete existing comments.

  • Anthony Steiner 5

    This probably the last one, and did 0 decent/useful additions to C#12, so sad that all the good things that we need and ask are being held because you still think that you know better of what are the things that should be added to the language, especially because primary constructors and interceptors had the most negative feedback I’ve seen, still made it, while the other things not even close, even some stuff talked in .NET 6, and .NET 7… or stuff like discriminated unions that we had been asking since forever. So sad that you are not listening, and we are getting a “release” with 0 real new (useful) things.

    • Vin 3

      Let’s hope atleast semi-auto-props (field keyword) will get into C# 12. Even though I am skeptical when looking at github activity regardless this feature. Having to use dummy backing fields feels so wrong to me.
      Also if list literals gets into release, list expansions like: [..list1, ..list2] seems to be pretty handy.

    • David Taylor 0

      They are listening Anthony. Primary constructors are awesome and I have been sending Microsoft feedback that I am very happy.

    • BellarmineHead 1

      If, from 2023 to 2024, the whole C# team worked together to add just one, large (and hard) feature – discriminated unions – it seems to me that the community would stand up and applaud. I know I would. Because it would deliver three things:-

      • a feature users actually want and have been asking for for years

      • a merciful lack of loads of piddly new microfeatures, which users have to (at least) assess, even if they are not used by many

      • an indication that the Microsoft can still listen to others, and not think they always know best

    • Kenneth Hoff 0

      Personally, I’m looking forward to the potential huge performance improvements from interceptors(even if the design leaves a lot to be desired), as well as the code simplification from primary constructors as well as connection literals. I don’t create collections that often out of static data, but the little I do will get simplified – which is great.

      I do wish Extensions, Discriminated Unions( or at the very least, a way to specify an exhaustive set), and Existential types (among others) would be implemented, but C# 12 – at least for me – does at valuable features (even if they aren’t as huge as say required properties)

  • Michael Dietrich 1

    Could interceptors be used to improve performance of LINQ expressions by unwrapping those as loops etc. if applicable?
    Usually LINQ is easier to read and more expressive, but slower due to IEnumerable and delegates.
    Would be nice to no longer replace LINQ by handwritten loops for better performance but worse readability.

    • Kathleen DollardMicrosoft employee 0

      It’s too early for a clear yes/no answer, but this is one of the areas identified in the proposal as potentially benefitting.

  • Jack Bond 3

    Literally everyone making these decisions should be FIRED IMMEDIATELY and be replaced with developers who are tackling real world issues.

    All this nonsense, and still no async constructors. Just unbelievable.

Feedback usabilla icon