BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News C# 11 Improvements for Strings, List Patterns and Object Creation

C# 11 Improvements for Strings, List Patterns and Object Creation

Bookmarks

As part of the .NET 7 launch, on November 8th Microsoft unveiled the new features of C# 11, the latest version of the popular .NET programming language. The most prominent improvements include string enhancements, static method abstractions, list patterns, and required members for object creation.

Raw string literals allow embedding strings with special characters or strings spanning multiple lines. In previous versions of .NET the developers had to escape special characters such as double quotes. In C# 11, multiple double quotes mark the beginning and the end of a raw string. The raw string literals can be combined with string interpolation using the $ character.

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

String interpolations can now span multiple lines, allowing for complex interpolation expressions such as switch statements.

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",
    }
  }";

A small update for strings in C# 11 is the ability to quickly specify a string literal as UTF-8 encoded, instead of the .NET default UTF-16 encoding, adding a u8 suffix to it. It creates a ReadOnlySpan<byte> representation of the string. UTF-8 is generally used in web standard protocols such as authentication.

ReadOnlySpan<byte> AuthStringLiteral = "AUTH "u8;

Static method abstractions in C# 11 allow developers to describe static abstract methods in interfaces, which permits writing generic parsing methods. .NET 7 team has used this feature to add support for generalising mathematical expressions in interfaces.

The pattern-matching capability of .NET expressions has been updated to support list patterns. While the existing pattern matching has focused on the properties of a single parameter, list patterns allow for matching a sequence of patterns to a list of elements.

int[] numbers = { 1, 2, 3 };

Console.WriteLine(numbers is [1, 2, 3]);  // True
Console.WriteLine(numbers is [1, 2, 4]);  // False
Console.WriteLine(numbers is [1, 2, 3, 4]);  // False
Console.WriteLine(numbers is [0 or 1, <= 2, >= 3]);  // True

List pattern matching is used by .NET 7 base class library in the previously mentioned generic mathematic interfaces.

Object initialisation calls are enhanced with the new required keyword for the class properties. C# 11 will raise a compile-time exception when creating an instance of the class without supplying values for the required members either in the constructor or in the object initialiser. This is allegedly the favourite new feature of C# 11 among the developers.

public class Person {
  public required string FirstName { get; set; }
  public string LastName { get; set; }
}

var p1 = new Person(); // Not valid
var p2 = new Person() { FirstName = "Edin" }; // Valid

For special cases such as positional records, there is a SetsRequiredMembers attribute to skip compiler checks for required properties.

While these new features for C# 11 are available in .NET 7, they can be tested in .NET 6 using the LangVersion project setting to preview.

About the Author

Rate this Article

Adoption
Style

Hello stranger!

You need to Register an InfoQ account or or login to post comments. But there's so much more behind being registered.

Get the most out of the InfoQ experience.

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Community comments

  • Ironic that the most broken feature is the favorite...

    by Sam King,

    Your message is awaiting moderation. Thank you for participating in the discussion.

    It's truly a shame that in 2022 the C# language team's standards have fallen to such a point that they're willing to ship hopelessly broken features like the `required` keyword. It is a total pit of failure. 10 years ago this feature would never have made it passed the drawing board.

    If you have required members and make a constructor that sets those members, you need to decorate the constructor with "SetsRequiredMembers"- an attribute which tells the compiler to not complain about members not being set. What the compiler does not do, however, is actually check that your constructor sets these members.

    This means that as your class gets subclassed or iterated on over time by adding new properties, your "SetsRequiredMembers" attribute will inevitably be telling a falsehood when someone forgets to initialize it in the constructor. Thus, just like with "non-null reference types", the `required` feature is merely a suggestion, not any kind of meaningful contract.

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

BT