A code editor with four icons symbolizing DevOps, developers, a gear, and a cluster.

This is the final article in our series about C# 11. You might not use the features in this article often in your own code, but you will definitely see them in library source code and code generated by source generators. In this article, we will discuss five new advanced features: UTF-8 string literals, file-scoped types, extended nameof support, generic attributes, and ref fields.

Follow the C# 11 series:

UTF-8 string literals

.NET uses UTF-16 encoding for the string type. Often, strings are actually stored and transferred as UTF-8 because that encoding requires fewer bytes.

C# 11 allows you to directly create the UTF-8 representation of a literal string by adding the u8 suffix:

ReadOnlySpan<byte> HttpGet = "GET"u8;

Previously, converting such literal strings to UTF-8 required either manually creating the corresponding byte array (or better, using a source generator) or using the Encoding.UTF8 class and paying a run-time cost.

This feature is interesting for libraries that implement protocols, such as ASP.NET Core.

File-scoped types

While implementing a type, you might want to move some logic into helper classes. Previously, such classes needed to be named or scoped in a way that would not conflict with other classes.

C# 11 enables types declared with file scope. These types won't be visible to any other files in the project. You'll see source-generators use this scope for internal helper types that are not meant to be used directly. Thanks to the file scope there can't be any name conflicts with other types defined or referenced by the project.

The following example shows a Console class that is visible only in the .cs file that contains it and doesn't cause name conflicts with System.Console in the rest of the project.

// Calls into the 'Console' class that is defined in this file.
Console.WriteLine("Hello, World!");

// This 'Console' class is not visible to other files.
file static class Console
{
   public static void WriteLine(string s) => System.Console.WriteLine(s);
}

Extended nameof

The nameof operator provides a convenient way to turn identifiers into strings.

C# 11 allows you to use parameter types and parameter names with nameof in method attributes. In previous versions, these identifiers were out of scope.

The following example shows how the NotNullIfNotNullAttribute attribute can be used to indicate that the method doesn't return null when the path argument is not null.

[return: NotNullIfNotNull(nameof(path))]
public static string? GetExtension(string? path)

Generic attributes

Previously, attributes could use types by directly using the Type class as a constructor argument or property. In C# 11, types can be used as generic attributes:

[MyAttribute<int>]
void Foo() { }

class MyAttribute<T> : Attribute { }

This enables a nicer syntax. The type specified as the argument must be fully known at compile time.

ref fields

The ref keyword indicates that a variable is passed by reference. Passing a variable by reference enables the called function to change the value of the variable in the calling function.

C# supports ref on a method argument or method return, as well as on a local variable:

int i = 10;

Foo(ref i);

ref int Foo(ref int j)
{
   ref int k = ref i;
   return ref j;
}

In this example, the parameter j and local k are aliases for int i. When you get their values i is read, and when you set their values i is set. The compiler guards the scope. For example, you are allowed to return ref j because the compiler knows that the variable referred to by the parameter will still be in scope. The compiler would not allow you to return ref k because the local ref could point to stack memory that goes out of scope when the method returns.

As we've just covered, ref variables can point to stack memory, which implies strict scoping rules. ref variables can also point to heap memory, which is managed by the garbage collector (GC). Like variables that have reference types, the GC tracks ref variables.

C# 8 (.NET Core 2.1) introduced ref struct and used it to implement Span. The Span type is an abstraction for memory that is on either the stack or the heap. A ref struct can live only on the stack.

To represent memory, Span needs two fields: a ref field that points to the first element of the memory and a length field to store the length of the memory.

In previous versions of .NET, the Span implementation was handled internally by the runtime.

C# 11 introduces ref fields as a first-class language concept. This construct lets you describe your Span type and define your own ref structs that have ref fields. For example, you can create a type that is used to read information from a large struct that can be on the stack, be on the heap, or even be unmanaged memory:

struct MyStruct { /* large struct */}

ref struct MyStructReader
{
   ref MyStruct _value;
   public MyStructReader(ref MyStruct value) => _value = ref value;
   ...
}

When you pass references to methods on a ref struct, the compiler ensures that the variables you refer to don't go out of scope before the struct itself. Otherwise, the ref struct might refer to out-of-scope variables:

void Process(ref MyStructReader reader)
{
   Span<byte> buffer = stackalloc byte[10];

   // error CS8352: Cannot use variable 'buffer' in this context because it may expose referenced variables outside of their declaration scope
   reader.ReadSomeValue(buffer);
   ...
}

You can tell the compiler to allow these variables to be passed in by adding the scoped keyword. The compiler then disallows storing these parameters in the struct:

ref struct MyStructReader
{
   ...
   public void ReadSomeValue(scoped Span<byte> value) { ... }
   ...

In other words, scoped tells the compiler to treat the argument with the same scope as a local variable in the method.

By default, this is a scoped ref. That definition makes it impossible to return references to its fields. To overcome that limitation, we can add the opposite of the scoped keyword: the UnscopedRef Attribute:

ref struct MyStructBuilder
{
   MyStruct _value;

   [UnscopedRef]
   ref MyStruct Value { get { EnsureInitialized(); return ref _value; } }
   ...

The C# 11 series concludes

In this final article of our C# 11 series, we looked at UTF-8 string literals, file-scoped types, extended nameof support, generic attributes, and ref fields. These new features improve C# for specific use cases.

We hope you have found this C# 11 series beneficial. As always, we welcome your feedback.

Last updated: December 10, 2023