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!
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.
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.
It’s too early for a clear yes/no answer, but this is one of the areas identified in the proposal as potentially benefitting.
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...
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 ...
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:-
They are listening Anthony. Primary constructors are awesome and I have been sending Microsoft feedback that I am very happy.
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.
Missing xml closed tags
Thanks! Fixed
Will C# 12 support ref struct to implement interface?
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...
So please invest into at least one larger feature
Discriminated unions. Grasp the nettle. Deliver something actually useful for a change! Do it.
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
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...
And the documentation, the last time I checked it was basically “read the code from those samples over there”.
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.
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
still no Discriminated Unions
C# 12 will not include Discriminated Unions.
I anticipate that we will continue to work on this in C# 13.
Any chance that extensions still gets into C#12?
I apologize for the delay. We met yesterday on our current best estimate of what will be in C# 12: https://github.com/dotnet/roslyn/discussions/69074
Unfortunately, implicit and explicit extensions (renamed from “roles and extensions”) will not be in C# 12.
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.
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.