What can we expect in C# 11?

02 september 2022 om 10:00 by ParTech Media - Post a comment

There is a popular saying - ‘Change is the only constant. It is applicable to most things, even to programming languages like C#.

We have arrived at that time of the year when this popular language is getting revamped. Yes, C# 11 is going to hit the market soon, and the world is eager to know how things are going to change.

In this blog, we are going to take you through some of the expected updates that will be rolled out as a part of C# 11.

Table of contents

  1. Enabling C# 11
  2. Features expected in C#11
  3. Conclusion

Enabling C#11

Microsoft released C#10 last year, along with .Net 6 and Visual Studio 2022. C# 11 is still in its preview phase, and it comes along with 17.1 - 17.3 versions of Visual Studio 2022. Users can install the latest version (17.3) and create a project based on the template of their choice. And to use C#11 from the preview mode, users need to add the below line to the project file.

<LangVersion>preview</LangVersion>

Note: The features that will be discussed in the next section might get released along with the C#11 or can be a part of the preview mode for a longer period.

Features expected in C#11

List patterns

C#11 provides the option to match an array or list of elements to a sequence in order to match the pattern. There are a few keystrokes that you need to understand to use List patterns -

  • (_) discard pattern - is a wild card for a single element. It means the element can be anything.
  • (..) range pattern - indicates that there could be zero to maximum elements in the sequence. And only one range pattern is allowed in a list pattern.
  • var pattern - is used to indicate a single or multiple range of elements.

To understand how it can be used, let’s consider the below example -

int[] one = { 1 };
int[] odd = { 1, 3, 5 };
int[] even = { 2, 4, 6 };
int[] fib = { 1, 1, 2, 3, 5 };

Pattern matching can be done through:

Console.WriteLine(odd is [1, 3, 5]); // true
Console.WriteLine(even is [1, 3, 5]); // false (values)
Console.WriteLine(one is [1, 3, 5]); // false (length)

With discard pattern:

Console.WriteLine(odd is [_, 3, _]); // true
Console.WriteLine(even is [_, _, 5]); // false (last value)

With discard and range together:

Console.WriteLine(odd is [1, _, 5, ..]); // true
Console.WriteLine(fib is [1, _, 5, ..]); // false

With discard and var pattern

Consider the below string:

04-01-2020, DEPOSIT, Initial deposit, 2250.00

The above string can be pattern matched using:

Console.WriteLine(“04-01-2020, DEPOSIT, Initial deposit, 2250.00” == [_, "DEPOSIT", _, var amount]);

UTF-8 string literals

Generally, strings in .Net are stored in UTF-16 encoding. However, for web protocols, UTF-8 encoding is followed as the standard. With C#11, if you need to use UTF-8 encoding, simply adding the suffix ‘u8’ will be enough. This will allow it to be encoded in the UTF-8 format.

ReadOnlySpan<byte> AuthWithTrailingSpace = new byte[] { 0x41, 0x55, 0x54, 0x48, 0x20 };
ReadOnlySpan<byte> AuthStringLiteral = "AUTH "u8;
byte[] AuthStringLiteral = "AUTH "u8.ToArray();

String interpolation does not support the u8 suffix. This means the $ token and u8 cannot be used in a single string.

Raw string literals

In C#11, without any escape sequence, one can store the text in a string just like it is achieved n a displayed format. This includes whitespace, new line, embedded quotes, and other special characters.

For example, in the past, if you needed to enter a string content in multiple lines, you needed to first use environment.newline explicitly at the instance where the new line is required. But with the new string literals, you can store the value as how it is required in the variable -

string longMessage = """
    This is a long message.
    It has several lines.
        Some are indented
                more than others.
    Some should start at the first column.
    Some have "quoted text" in them.
    """;

The raw string literals are denoted with at least three double quotes (”””) characters. It ends with the same number of double quote characters in the same line or a different line. The new line preceding the opening quote and any space/line before the ending quote is ignored in the final content.

The output of the above line code like this -

String interpolation can be combined with the raw string literals like this -

int Longitude = 0 ;
int Latitude = 1;
var location = $$"""
   You are at {{{Longitude}}, {{Latitude}}}
   """;

The number of $ characters before the double quotes indicates the consecutive start and end braces used in the interpolation.

Output:

New lines in String interpolation

String interpolation is a known concept since C#6. However, it never had the capability to include new lines within the curly braces (interpolation expression). But starting with C#11, new lines can be introduced within the curly braces { }.

There are two types of string interpolation - verbatim interpolation and non-verbatim interpolation. Verbatim interpolation is the one with $@ preceding the string data, while non-verbatim interpolation is the one with $ alone preceding the string data.

Verbatim string interpolation can hold new lines in the text segment, while non-verbatim requires the help of escape characters to include new lines in the interpolation.

In C# 11, non-verbatim string interpolation can include new lines without any escape characters.

Here is an example -

var safetyScore = 75;

            string message = $"The usage policy for {safetyScore} is {safetyScore switch
            {
                > 90 => "Unlimited usage",
                > 80 => "General usage, with daily safety check",
                > 70 => "Issues must be addressed within 1 week",
                > 50 => "Issues must be addressed within 1 day",
                _ => "Issues must be addressed before continued use",
            }}";

Within the interpolation, new lines are added, which increases the readability of the code.

Output:

Struct with default values

C#11 compiler provides the option to compile the fields (or auto-properties) that are not initialized by the constructor in a struct. The compiler implicitly assigns default values to the fields (or auto-properties) that are not initialized in the constructor explicitly.

Conclusion

And that’s everything you need to know about the expected features in C#11. But this could be just the tip of the iceberg. You can expect a lot more features that might make the lives of developers way simpler.

Nieuwste