This article is the first in a series in which we'll look at the new features of C# 11. Released in November of 2022, .NET 7 includes support for C# 11, a new major version of the C# programming language. In this article, we'll look at interpolated strings, required members, and auto-default structs. These features can be used in everyday programs.
Follow the C# 11 series:
- Part 1: Raw strings, required members, and auto-default structs
- Part 2: Pattern matching and static abstract interfaces
- Part 3: 5 new advanced features improving C# 11
Raw string literals
Before we look at the new C# features, let's recap how interpolated strings evolved across C# versions.
In early C#, adding values in a string was performed using format strings. A format string contains placeholders that are then substituted by values. Methods like string.Format()
and Console.WriteLine()
support this pattern.
Console.WriteLine("{0} is {1} years old", person.Name, person.Age);
Because braces are used for placeholders, the string formatter allows adding literal braces by using double braces ({{
or }}
) in the format string.
A backslash is used to add quotes and other special characters like newlines into the string (\n
, \
, \\
).
To avoid backslash-escaping, C# also supports verbatim strings using the @"
specifier. All characters are treated literally (including newlines). Quotes can be added using double quotes.
string s =
@"The paths are:
{""C:\dir1"",
""C:\dir2""}";
With C# 6 (.NET 4.6), string interpolation became a language feature using the $”
specifier.
Console.WriteLine($"{person.Name} is {person.Age} years old");
As with format strings, double braces must be used to add literal braces to the string.
Since .NET 6, such interpolated strings are handled very efficiently by the compiler and avoid boxing and allocations that take place when using the Format
methods (which take their values as an object
array).
Interpolated strings didn't allow the use of newlines in their expressions. Because these expressions are regular C#, this was an artificial limitation that has been removed in C# 11.
// C# 11 allows using newlines in interpolated string expressions.
Console.WriteLine($"The first person is {people.OrderBy(s => s.Name)
.First()}");
Interpolated strings can be combined with verbatim strings, like so:
string paths =
$@"The paths are:
{{""C:\{dir1}"",
""C:\{dir2}""}}";
As with regular interpolated strings, literal braces need to be escaped as double braces.
As shown in the previous example, in .NET 6 we were still required to escape quotes and braces. These characters are common in data formats like JSON and XML. C# 11 introduces raw string literals, which enable the use of these data formats directly without any escaping.
string json= """
{
name: "John",
age: 49
}
""";
A raw literal string starts with three or more quote characters, and it is terminated by the same number of quotes on a line. Anything appearing inside the string with fewer quotes is verbatim, like the quotes surrounding "John"
.
In this string, the newline after the starting quotes and the newline before the ending quotes are not considered part of the string. The indentation before the ending quotes is discarded over all lines.
Raw literal strings can be interpolated by prefixing with a $
. As with the quotes, the number of dollar signs can be changed to control the number of braces needed for an expression. Fewer braces appear verbatim in the output.
string json= $$"""
{
name: {{name}},
age: {{age}}
}
""";
In this example, we've used two dollar signs to make the single braces appear literal and to use double braces for interpolated expressions.
Required members
C# 9 introduced init
accessors to create immutable objects. Unlike a set
accessor, the init
accessor can only be used while constructing the object.
class Person
{
public string Name { get; init; }
public DateTime BirthDay { get; init; }
}
Person john = new Person { Name = "John", BirthDay = new DateTime(1970, 4, 1) };
john.BirthDay = DateTime.Now; // error: can only be assigned in object initializer
If you have nullable
enabled for your project, the compiler will give a warning for this code:
Non-nullable property 'Name' must contain a non-null value when exiting constructor.
To get rid of the warning, we could add a constructor that accepts the name as an argument. However, that would force us to use a different syntax for initializing the object. Another option is to initialize the property with null!
.
public string Name { get; init; } = null!;
This silences the nullable warning without fixing it.
C# 11 gives us a new option: we can mark properties (and fields) as required
.
class Person
{
public required string Name { get; init; }
public DateTime BirthDay { get; init; }
}
var person = new Person() { Name = "John" };
The compiler will require all required members to be set in the object initializer. If we leave out Name
from the initializer, we'll get an error.
If the type also has a constructor, the compiler will still require that these members be added to the initializer. You can tell the compiler this is not needed by marking the constructor with the SetRequiredMembers
attribute (from System.Diagnostics.CodeAnalysis
).
class Person
{
public required string Name { get; init; }
public DateTime BirthDay { get; init; }
[SetsRequiredMembers]
public Person(string name) => Name = name;
}
The compiler uses this attribute when analyzing the call to the constructor. It doesn't verify that the constructor actually initializes the members. This is similar to other analyses (like when tracking nullable).
Auto-default structs
In previous versions of C#, when you add a constructor to a struct, the compiler requires you to initialize all fields. Consider the following example:
struct MyStruct
{
private int _field;
public MyStruct()
{ }
}
This would give an error because _field
is not initialized in the constructor. C# 11 no longer requires this: all fields that are not initialized in the constructor will be set to their default
value.
Note that this example uses a parameterless constructor. This is a constructor that C# supports in C# 10 and all subsequent versions of the language. Before that, all user-defined constructors required arguments, and the default constructor would always initialize all fields to default
. Auto-default fields apply to all constructors.
Conclusion
In this first article on C# 11, we looked at raw string literals, required members, and auto-default structs. You'll find these new features useful in your everyday C# development. The next article describes two features: pattern matching and static abstract interfaces and how they enable generic math.
Last updated: January 10, 2023