Featured image for .NET

This is the first article in a two-part series that looks at the new features of C# 12. C# 12 is supported by the .NET 8 SDK, which was released in November 2023. The features described in this article are usable in everyday programs. In the second article, we’ll cover advanced features for specific use cases.

Collection expressions

Collection expressions are a new syntax to initialize a collection type. The syntax consists of square brackets ([, ]) that surround the collection items as shown in the following examples:

// Initialize a variable
int[] arrayOfInt = [1, 2, 3];

// Initialize an argument
Foo(["one", "two", "three"]);

These types can be initialized from a collection expression:

  • Array types
  • Span<T>, ReadOnlySpan<T>
  • Types that implement IEnumerable<T>, have a public parameterless constructor, and have an Add method that matches (or implicitly converts to) the item type, like List<T>
  • IEnumerable<T>, (IReadOnly)Collection<T>, (IReadOnly)List<T>

The compiler will optimize the generated code based on the target type and the initializer expression.

It’s possible to include the items from an enumerable expression in a collection expression by using the spread operator (..). The following example creates a list starting with the string first, followed by the items from list1 and list2, and final as the last item.

List<string> composedList = ["first", ..list1, ..list2, "final"];

Support for collection expression initialization can be explicitly implemented for a type using the CollectionBuilder attribute. The CollectionBuilder attribute points to a method that accepts a ReadOnlySpan<T> and creates the collection type from it. This is shown in the following example.

[CollectionBuilder(typeof(MyListBuilder), "Create")]
public class MyList : IEnumerable<string> {
  private readonly List<string> _items;

  internal MyList(List<string> items)
    => _items = items;

  public IEnumerator<string> GetEnumerator()
    => _items.GetEnumerator();

  IEnumerator IEnumerable.GetEnumerator()
    => _items.GetEnumerator();
}

internal static class MyListBuilder {
  internal static MyList Create(ReadOnlySpan<string> values)
    => new MyList([..values]);
}

Primary constructors

As part of the record and record struct features introduced in C# 9 and C# 10 a terse syntax was included to declare a constructor, called a primary constructor.

record struct Point(int X, int Y)
{ }

Point point = new(5, 3);
int x = point.X;

The primary constructor syntax can now also be used on regular (non-record) class and struct declarations.

class MyController(IHttpClientFactory clientFactory)
{
   public ActionResult Get()
   {
      var client = clientFactory.CreateClient("orders");
      ...

As shown in the previous example, the parameters of the primary constructor can be used throughout the class body.

For record and record struct declarations the compiler automatically generates public properties for the constructor parameters. For (non-record) class and struct declarations no corresponding public properties are generated. When the parameters are used in the type body, they are stored in a private field.

This difference in behavior is desired. record and record class are meant for creating “simple” types that represent values. The values that are passed to the constructor are therefore directly exposed as properties. For class and struct the new syntax wants to continue to allow accepting the parameters for use in the type implementation without requiring to expose them.

A common code style is to distinguish between parameters and field names using a leading underscore for the latter. If desired, this can be achieved by declaring the backing field explicitly as shown in the following example.

class MyController(IHttpClientFactory clientFactory)
{
  private readonly IHttpClientFactory _clientFactory = clientFactory;
  ...

Another option is to use a constructor parameter to initialize a property.

class MyController(IHttpClientFactory clientFactory)
{
    private IHttpClientFactory ClientFactory { get; } = clientFactory;

If the parameter is passed to a base class and captured by the base class body, the derived class shouldn’t use the constructor parameter in its body because then the base class and the derived class will store their own version of the parameter. The compiler will generate a CS9107 warning when it detects this. Instead, the derived class should access the parameter using the backing field/property as shown in the next example.

class MyController(IHttpClientFactory clientFactory) : Base(clientFactory)
{
  public ActionResult Get()
  {
    var client = _clientFactory.CreateClient("orders");
     ...
  }
}

class Base(IHttpClientFactory clientFactory)
{
  protected readonly IHttpClientFactory _clientFactory = clientFactory;
}

When additional constructors are added to a type, they must call the primary constructor using this(..). This ensures that all primary constructor parameters are assigned.

class MyController(IHttpClientFactory clientFactory)
{
  public MyController() : this(CreateDefaultClientFactory())
  { }

Attributes can be added to the primary constructor. By default, attributes preceding the class or struct target the type. To target the primary constructor, the method: prefix can be used, as shown in the following example.

[method: Obsolete("Use an other constructor.")]
class MyController(IHttpClientFactory clientFactory)
{

Conclusion

In this article on C# 12, we looked at collection expressions, which provide a terse syntax to initialize a collection type composed of items and items from other collections using the new spread operator. We also learned about primary constructors that enable a terse syntax to declare a constructor on a class or struct types. Both these features are useful in everyday C# development.

In the next article, we’ll look at advanced features introduced in C# 12.

Last updated: April 30, 2024