Home > What’s New in C# 11?
Anthony Alliot
8 November 2022
Lire cet article en Français

What’s New in C# 11?

What’s New in C# 11?

C# 11 will be released in November—at the same time as .NET 7—and like previous iterations, it will include a number of useful new features.

In this post, I want to look at some of C# 11’s new features (you can find the full list here: What’s new in C# 11 – C# Guide | Microsoft Learn)

 

Generic Attributes

 

You can now declare a generic attribute class.

 

Before C# 11:

 

With C# 11:

 

Note: arguments of the following types are not allowed:

  • dynamic
  • string?
  • (string x, string y)

They must be replaced with:

  • “Object” rather than “dynamic”
  • “string” rather than “string?” (“Nullable” is not an allowed type)
  • “ValueTuple<string, string>” rather than “(string x, string y)”

 

Required Members

 

You can add the “required” modifier to a class’s properties to make their initialization mandatory.

 

Raw String Literals

 

This new string format lets you use spaces, line breaks, and some special characters. These strings start and end with three double quotes (“””). You can also use string interpolation with this format to include “{” in the text. The number of “$” indicates how many consecutive braces start and end the interpolation.

 

Line Feed in String Interpolation

 

You can use this feature to include a line break in a string in the interpolation.

 

Before C# 11 (all the code is on the same line):

 

With C# 11:

 

UTF-8 String Literals

 

It is now easier to create UTF-8 strings.

 

Before C# 11:

byte[] array = Encoding.UTF8.GetBytes("Hello World");

 

With C# 11:

byte[] array = "Hello World"u8.ToArray();

 

Extended Nameof Scope

 

Type parameter names are now available in the “nameof” scope when declaring an attribute:

 

List Patterns

 

List patterns extend pattern matching to include matching with sequences of elements in a list or an array.

 

New Keyword: “file”

 

This new keyword lets you create a type that can only be seen in the file where it is declared. In the example below, the “User” class can’t be instantiated outside this CS file:

 

Expert Opinion on What’s New in C# 11

 

So, that concludes our overview of most of the new features in C# 11. Some of them are more useful than others. I already know that features 1 (generic attributes), 2 (required members), and 4 (line feed in string interpolation) will be helpful when I switch to C# 11.

Want to learn more about the new features in .NET 7? Read our other posts on this subject:

This posts should interest you
Comments
Leave a Reply

Receive the best of Cloud, DevOps and IT news.
Receive the best of Cloud, DevOps and IT news.