As you may have already heard, Microsoft released .NET 7 two weeks ago. In addition to changes to the performance of NET, there are also features for the primary language of that framework – I mean C#. Today, I would like to write a bit about additions to C# 11 which are, in my opinion, the most interesting.
For exploring these features, you need to install the newest version of Visual Studio 2002 Preview and .NET 7 SDK.
First of all, it’s called list patterns but, of course, it applies to anything with a count property, for example – arrays. So let’s start playing with that feature.
We have the following list:
As you can see on that listing, there are some example patterns and we are going to check if they match our list. So let me check what our console returns:
It works fine and can be useful for some specific cases in our apps. Such features always are a good thing that saves us time. Instead of writing another helper, we can focus on much more important parts of our application, right?
Generics on attributes
You have the option to declare a generic class whose base class is System.Attribute. This feature provides a smoother syntax for attributes that require a System.Type parameter. In the previous version, you had to create an attribute that takes Type as its constructor parameter:
And to apply the attribute, you needed to use the typeof operator:
Now you can close it in such a nice form:
And then, just specify the type parameter to use the attribute:
Another valuable feature is about adding the required modifier to properties and fields to enforce constructors and callers to initialize those values. The System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute can be added to constructors to notify the compiler that a constructor initializes all required members.
Take a look at the graphic below – when creating a new instance of the Home class, we receive an error that a property containing the required keyword needs to be added.
Well, I have presented the most interesting features, in my opinion, from C#, for the rest, go to the Microsoft blog. In addition, I invite you to read my latest blog post about creating applications using Blazor and .NET MAUI. See you soon!