July 11th, 2023

New C# 12 preview features

Kathleen Dollard
Principal Program Manager

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!

Category
.NETC#

Author

Kathleen Dollard
Principal Program Manager

Kathleen Dollard loves to code and loves to teach and talk about code. She’s written tons of articles, a book, and spoken around the world. She’s on the .NET Team at Microsoft where she works on the .NET Core CLI and SDK and managed languages (C# and Visual Basic.NET). She’s always ready to help developers take the next step in exploring the wonderful world we call code.

34 comments

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

  • Jack Bond

    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.

  • Michael Dietrich

    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 Author

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

  • Anthony Steiner

    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...

    Read more
    • Kenneth Hoff

      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 , ( or at the very least, a way to specify an exhaustive set), and ...

      Read more
    • BellarmineHead

      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:-

      Read more
    • David Taylor

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

    • Vin

      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.

  • pot summ · Edited

    Missing xml closed tags

    <PropertyGroup>
       <Features>InterceptorsPreview<Features>
    </PropertyGroup>
    
  • gc y

    Will C# 12 support ref struct to implement interface?

  • Martin Sedlmair

    Thanks for the hard work. But to be honest I can see nothing I can benefit from. Most things are syntactic sugar which of course help and I admit that there have been things (like records) I didn't find useful at the beginning. But I can see nothing in https://learn.microsoft.com/en-my/dotnet/csharp/whats-new/csharp-12 that allows me to do things I can currently not do, things, that help me to improve code quality/readability and to prevent people from...

    Read more
    • BellarmineHead

      So please invest into at least one larger feature

      Discriminated unions. Grasp the nettle. Deliver something actually useful for a change! Do it.

      • Kathleen DollardMicrosoft employee Author

        We did design work in this cycle on roles and extensions that led to our now considering them as implicit and explicit extensions. We think this perspective will help us move forward in this important space.

        We also worked on discriminated unions, and hope both can move forward next year.

        You can find out more about his process in the LDM notes: https://github.com/dotnet/csharplang/tree/main/meetings/2023

        Read more
  • MgSam

    Surprised Interceptors made it to a Preview state given how negative the feedback was on Github.

    I think Microsoft still needs to go back to the drawing board here. Source generators suck. They have terrible performance, they're hard to write, near impossible to debug, run non-deterministically, and have limited use cases. They are a failure and tweaking around the edges to try and eek out slightly better perf doesn't seem like its going to fix most...

    Read more
    • Paulo Pinto

      And the documentation, the last time I checked it was basically “read the code from those samples over there”.

    • Sedlmair, Martin (SHS DI CT R&D CTC SA)

      Agreed. Since in every proposal that could be a language feature, the C# language team proposes to write analyzers or source generators instead too offload the lack of development resources in the c# language team to the regular user. If this is the way, then I agree that development analyzers and source generators must be easier and not having to restart VS again and again so that the new analyzer is getting active.

      • Alexander Gayko

        hey Martin,
        i solved this issue and released the "fix" as an extension:
        https://marketplace.visualstudio.com/items?itemName=AlexanderGayko.AutoUpdateAssemblyName
        please promote it :-P

        Having said that, the reasoning behind generators working as they do and being dev'ed as they do (with unit tests in mind) is not wrong - it's just inconvenient for people wanting to build (and move on) their own SGs for themselves. Please chime in in the discussion over in the c# discord in the roslyn channel.

        thanks,
        Alex

        Read more
  • W L

    still no Discriminated Unions

    • Kathleen DollardMicrosoft employee Author

      C# 12 will not include Discriminated Unions.

      I anticipate that we will continue to work on this in C# 13.

  • Renee GA

    Any chance that extensions still gets into C#12?

  • Praveen Potturu

    Regarding interceptors, do they get to see code generated by the source generators? I am asking because I am working on a source generator that generates calls to MapGet, MapPost etc.

    • Kathleen DollardMicrosoft employee Author

      Interceptors use normal source generators. So, like all other generators, their source generators cannot see the output of other source generators. However, they are also normal C# code (with an attribute that leads to special handling), so the code within an interceptor can access the output of other source generators.