What's new in C# 11ΒΆ
[!IMPORTANT] These are currently preview features. You must set
<LangVersion>
topreview
to enable these features. Any feature may change before its final release. These features may not all be released in C# 11. Some may remain in a preview phase for longer based on feedback on the feature.
The following feature is available in Visual Studio 2022 version 17.4:
The following features are available in Visual Studio 2022 version 17.3:
- What's new in C# 11
- Generic attributes
- Generic math support
- Numeric
IntPtr
andUIntPtr
- Newlines in string interpolations
- List patterns
- Improved method group conversion to delegate
- Raw string literals
- Auto-default struct
- Pattern match
Span<char>
orReadOnlySpan<char>
on a constantstring
- Extended nameof scope
- UTF-8 string literals
- Required members
ref
fields andref scoped
variables- File scoped types
The following features are available in Visual Studio 2022 version 17.2:
The following features are available in Visual Studio 2022 version 17.1:
You can download the latest Visual Studio 2022. You can also try all these features with the preview release of the .NET 7 SDK, which can be downloaded from the all .NET downloads page.
Generic attributesΒΆ
You can declare a generic class whose base class is Type
as its constructor parameter:
// Before C# 11:
public class TypeAttribute : Attribute
{
public TypeAttribute(Type t) => ParamType = t;
public Type ParamType { get; }
}
And to apply the attribute, you use the typeof
operator:
Using this new feature, you can create a generic attribute instead:
Then, specify the type parameter to use the attribute:
You must supply all type parameters when you apply the attribute. In other words, the generic type must be fully constructed.
public class GenericType<T>
{
[GenericAttribute<T>()] // Not allowed! generic attributes must be fully constructed types.
public string Method() => default;
}
The type arguments must satisfy the same restrictions as the typeof
operator. Types that require metadata annotations aren't allowed. For example, the following types aren't allowed as the type parameter:
dynamic
string?
(or any nullable reference type)(int X, int Y)
(or any other tuple types using C# tuple syntax).
These types aren't directly represented in metadata. They include annotations that describe the type. In all cases, you can use the underlying type instead:
object
fordynamic
.string
instead ofstring?
.ValueTuple<int, int>
instead of(int X, int Y)
.
Generic math supportΒΆ
There are several language features that enable generic math support:
static virtual
members in interfaces- checked user defined operators
- relaxed shift operators
- unsigned right-shift operator
You can add static abstract
or static virtual
members in interfaces to define interfaces that include overloadable operators, other static members, and static properties. The primary scenario for this feature is to use mathematical operators in generic types. For example, you can implement the System.IAdditionOperators<TSelf, TOther, TResult>
interface in a type that implements operator +
. Other interfaces define other mathematical operations or well-defined values. You can learn about the new syntax in the article on interfaces. Interfaces that include static virtual
methods are typically generic interfaces. Furthermore, most will declare a constraint that the type parameter implements the declared interface.
You can learn more and try the feature yourself in the tutorial Explore static abstract interface members, or the Preview features in .NET 6 β generic math blog post.
Generic math created other requirements on the language.
- unsigned right shift operator: Before C# 11, to force an unsigned right-shift, you would need to cast any signed integer type to an unsigned type, perform the shift, then cast the result back to a signed type. Beginning in C# 11, you can use the
>>>
, the unsigned shift operator. - relaxed shift operator requirements: C# 11 removes the requirement that the second operand must be an
int
or implicitly convertible toint
. This change allows types that implement generic math interfaces to be used in these locations. - checked and unchecked user defined operators: Developers can now define
checked
andunchecked
arithmetic operators. The compiler generates calls to the correct variant based on the current context. You can read more aboutchecked
operators in the article on Arithmetic operators.
Numeric IntPtr
and UIntPtr
ΒΆ
The nint
and nuint
types now alias
Newlines in string interpolationsΒΆ
The text inside the {
and }
characters for a string interpolation can now span multiple lines. The text between the {
and }
markers is parsed as C#. Any legal C#, including newlines, is allowed. This feature makes it easier to read string interpolations that use longer C# expressions, like pattern matching switch
expressions, or LINQ queries.
You can learn more about the newlines feature in the string interpolations article in the language reference.
List patternsΒΆ
List patterns extend pattern matching to match sequences of elements in a list or an array. For example, sequence is [1, 2, 3]
is true
when the sequence
is an array or a list of three integers (1, 2, and 3). You can match elements using any pattern, including constant, type, property and relational patterns. The discard pattern (_
) matches any single element, and the new range pattern (..
) matches any sequence of zero or more elements.
You can learn more details about list patterns in the pattern matching article in the language reference.
Improved method group conversion to delegateΒΆ
The C# standard on Method group conversions now includes the following item:
- The conversion is permitted (but not required) to use an existing delegate instance that already contains these references.
Previous versions of the standard prohibited the compiler from reusing the delegate object created for a method group conversion. The C# 11 compiler caches the delegate object created from a method group conversion and reuses that single delegate object. This feature is first available in Visual Studio 17.2 as a preview feature. It's first available in .NET 7 preview 2.
Raw string literalsΒΆ
Raw string literals are a new format for string literals. Raw string literals can contain arbitrary text, including whitespace, new lines, embedded quotes, and other special characters without requiring escape sequences. A raw string literal starts with at least three double-quote (""") characters. It ends with the same number of double-quote characters. Typically, a raw string literal uses three double quotes on a single line to start the string, and three double quotes on a separate line to end the string. The newlines following the opening quote and preceding the closing quote aren't included in the final content:
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.
""";
Any whitespace to the left of the closing double quotes will be removed from the string literal. Raw string literals can be combined with string interpolation to include braces in the output text. Multiple $
characters denote how many consecutive braces start and end the interpolation:
The preceding example specifies that two braces start and end an interpolation. The third repeated opening and closing brace are included in the output string.
You can learn more about raw string literals in the article on strings in the programming guide, and the language reference articles on string literals and interpolated strings.
Auto-default structΒΆ
The C# 11 compiler ensures that all fields of a struct
type are initialized to their default value as part of executing a constructor. This change means any field or auto property not initialized by a constructor is automatically initialized by the compiler. Structs where the constructor doesn't definitely assign all fields now compile, and any fields not explicitly initialized are set to their default value. You can read more about how this change affects struct initialization in the article on structs.
Pattern match Span<char>
or ReadOnlySpan<char>
on a constant string
ΒΆ
You've been able to test if a string
had a specific constant value using pattern matching for several releases. Now, you can use the same pattern matching logic with variables that are Span<char>
or ReadOnlySpan<char>
.
Extended nameof scopeΒΆ
Type parameter names and parameter names are now in scope when used in a nameof
expression in an attribute declaration on that method. This feature means you can use the nameof
operator to specify the name of a method parameter in an attribute on the method or parameter declaration. This feature is most often useful to add attributes for nullable analysis.
UTF-8 string literalsΒΆ
You can specify the u8
suffix on a string literal to specify UTF-8 character encoding. If your application needs UTF-8 strings, for HTTP string constants or similar text protocols, you can use this feature to simplify the creation of UTF-8 strings.
You can learn more about UTF-8 string literals in the string literal section of the article on builtin reference types.
Required membersΒΆ
You can add the required
modifier to properties and fields to enforce constructors and callers to initialize those values. The
For more information on required members, See the init-only section of the properties article.
ref
fields and ref scoped
variablesΒΆ
You can declare ref
fields inside a ref struct
. This supports types such as
You can add the scoped
modifier to any ref
declaration. This limits the scope where the reference can escape to.
File scoped typesΒΆ
Beginning in C# 11, you can use the file
access modifier to create a type whose visibility is scoped to the source file in which it is declared. This feature helps source generator authors avoid naming collisions. You can learn more about this feature in the article on file-scoped types in the language reference.