C# 11 Features

This article will explain some new C# 11 features that will make it simpler for you to write faster, clearer, and more expressive code. C# is one of the established and most widely used programming languages in the world. The new C# 11 features and enhancements mentioned here will make it simpler and quicker for programmers to write cleaner, more readable code. We'll examine each one separately with an illustration. C# 11 is the latest version of C# language, it was released with the latest .Net 7.


C# 11 is supported on .NET 7 and Visual Studio 2022. Some of the top new features in C# 11 are listed below:



·        Required Members


·        Raw string Literals


·        UTF-8 string literals


·        List patterns


·        Newlines in string interpolations


·        Pattern match Span<char> on a constant string




Let’s look at each of these features in C# 11.


Required Members:


The required modifier indicates that the field or property it's applied to must be initialized by all constructors or by using an object initializer. Any expression that initializes a new instance of the type must initialize all required members. C# 11 introduces a new required modifier to fields & properties to impose constructors & callers to initialize those values.

A new SetsRequiredMembers attribute on the constructor tells the compiler that it initializes all required members.


// Initializations with required properties

var p1 = new Person { Name = "fida", Surname = "hussain" };

Person p2 = new("fida", "hussain");


// Initializations with missing required properties

var p3 = new Person { Name = "fida" };

Person p4 = new();

// Error CS9035: Required member `Person.Name` must be set:

//person p3 = new Person();


public class Person

{

    public Person() { }


    [SetsRequiredMembers]

    public Person(string name, string surname)

    {

        Name = name;

        Surname = surname;

    }


    public Guid Id { get; set; } = Guid.NewGuid();

    public required string Name { get; set; }

    public required string Surname { get; set; }

}





Raw string Literals :


A new format for string literals is called raw string literals. Without the need for escape sequences, raw string literals can contain any text, including new lines, embedded quotations, whitespace, and other special characters. There are at least three double-quotes (""") characters at the beginning of a raw string literal. The same amount of double-quote characters is used to close it. A raw string literal typically begins with three double quotes on a single line and ends with three double quotes on a different line.

It allows containing arbitrary text without escaping.

The format is minimum 3 double quotes """.."""

The count of $ indicates how many braces in a row begin and terminate the interpolation, which works in combining with string interpolation.


C# 10

string name = "Md Fida";

string surname = "Hussain";


string rawString =

  $@"

  {{

    'Name': {name},

    'Surname': {surname}

  }}

  ";


Console.WriteLine(rawString);



C# 11

Given below is an example of raw string literals.

string name = "fida";

string surname = "hussain";


string rawString =

  $$"""

  {

    "Name": {{name}},

    "Surname": {{surname}}

  }

  """;

Console.WriteLine(rawString);


Output:

fida hussain



UTF-8 string literals:


A string literal can have the u8 suffix to express UTF-8 character encoding. This feature makes it easier to create UTF-8 strings if your application requires them for HTTP string constants or other text protocols. It allows converting only UTF-8 characters to their byte representation at compile time.


C# 10


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





C# 11


byte[] array = "Hello World";




List Patterns:


Sequences of elements in a list or an array can be matched using list patterns, which is an extension of pattern matching. For example, the sequence [1, 2, 3] is true when the sequence is an array or a list of three integers (1, 2, and 3). Any pattern, including relational, type, constant, and property patterns, can be used to match elements. The new range pattern (..) matches any sequence of zero or more elements, whereas the discard pattern (_) matches any single element.

C# 11

var numbers = new[] { 1, 2, 3, 4 };

// List and constant patterns

Console.WriteLine(numbers is [1, 2, 3, 4]); // True

Console.WriteLine(numbers is [1, 2, 4]); // False


// List and discard patterns

Console.WriteLine(numbers is [_, 2, _, 4]); // True

Console.WriteLine(numbers is [.., 3, _]); // True


// List and logical patterns

Console.WriteLine(numbers is [_, >= 2, _, _]); // True





Newlines in string interpolations:


For a string interpolation, text inside the { and }  characters can now span multiple lines. From now onwards newlines are also accepted between {  and   } characters. Longer C# expressions, such as pattern matching switch expressions or LINQ queries, that are used in string interpolations can now be read more easily thanks to this capability.

var day = 1;

Console.WriteLine(

   

    $"""

     Today is : "{day switch

    {

        1 => "sunday",

        2 => "monday",

        3 => "tuesday",

        4 => "wednesday",

        5 => "thursday",

        6 => "friday",

        7 => "saturday",

        _=> "wrong choice ! try again"

    }

     }"

    """);


Output:

Today is : sunday




Pattern match Span<char> on a constant string:


For several releases, pattern matching has allowed you to check whether a string has a particular constant value. Now, you can use the same pattern-matching logic with variables that are Span<char> or ReadOnlySpan<char>. Using pattern matching, we can test if the string has a certain constant value in C#.


C# 10

ReadOnlySpan<char> strSpan = "Solutions".AsSpan();

if (strSpan == "Solutions")

{

    Console.WriteLine("CodeTo, Solutions");

}



C# 11

ReadOnlySpan<char> strSpan1 = "Solutions".AsSpan();

if (strSpan1 is "Solutions")

{

    Console.WriteLine("CodeTo, Solutions");

}


Output:

CodeTo, Solutions




Conclusion:


The new C# 11 features that came with the release of the new version of C# were covered in this article. Because they appear to alter how we approach and develop C# projects, some of these enhancements appear to be very essential. These features will help us to solve our tasks in a more easiest and simple way.

hope you enjoyed reading this article and found it useful. Please share your thoughts and recommendations in the comment section below.


Share This Post

Linkedin
Fb Share
Twitter Share
Reddit Share

Support Me

Buy Me A Coffee