Skip to main content
Redhat Developers  Logo
  • Products

    Featured

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat OpenShift AI
      Red Hat OpenShift AI
    • Red Hat Enterprise Linux AI
      Linux icon inside of a brain
    • Image mode for Red Hat Enterprise Linux
      RHEL image mode
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • Red Hat Developer Hub
      Developer Hub
    • View All Red Hat Products
    • Linux

      • Red Hat Enterprise Linux
      • Image mode for Red Hat Enterprise Linux
      • Red Hat Universal Base Images (UBI)
    • Java runtimes & frameworks

      • JBoss Enterprise Application Platform
      • Red Hat build of OpenJDK
    • Kubernetes

      • Red Hat OpenShift
      • Microsoft Azure Red Hat OpenShift
      • Red Hat OpenShift Virtualization
      • Red Hat OpenShift Lightspeed
    • Integration & App Connectivity

      • Red Hat Build of Apache Camel
      • Red Hat Service Interconnect
      • Red Hat Connectivity Link
    • AI/ML

      • Red Hat OpenShift AI
      • Red Hat Enterprise Linux AI
    • Automation

      • Red Hat Ansible Automation Platform
      • Red Hat Ansible Lightspeed
    • Developer tools

      • Red Hat Trusted Software Supply Chain
      • Podman Desktop
      • Red Hat OpenShift Dev Spaces
    • Developer Sandbox

      Developer Sandbox
      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Secure Development & Architectures

      • Security
      • Secure coding
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
      • View All Technologies
    • Start exploring in the Developer Sandbox for free

      sandbox graphic
      Try Red Hat's products and technologies without setup or configuration.
    • Try at no cost
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • Java
      Java icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • API Catalog
    • Product Documentation
    • Legacy Documentation
    • Red Hat Learning

      Learning image
      Boost your technical skills to expert-level with the help of interactive lessons offered by various Red Hat Learning programs.
    • Explore Red Hat Learning
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

C# 12: Collection expressions and primary constructors

April 22, 2024
Tom Deseyn
Related topics:
Linux
Related products:
Red Hat Enterprise Linux

Share:

    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

    Related Posts

    • Some more C# 12

    • C# 11: Raw strings, required members, and auto-default structs

    • C# 11: Pattern matching and static abstract interfaces

    • C# 9 top-level programs and target-typed expressions

    • C# 9 init accessors and records

    • Containerize .NET applications without writing Dockerfiles

    Recent Posts

    • More Essential AI tutorials for Node.js Developers

    • How to run a fraud detection AI model on RHEL CVMs

    • How we use software provenance at Red Hat

    • Alternatives to creating bootc images from scratch

    • How to update OpenStack Services on OpenShift

    What’s up next?

    Advanced Linux Commands tile card - updated

    Level up your Linux knowledge: This cheat sheet presents a collection of Linux commands and executables for developers who are using the Linux operating system in advanced programming scenarios. 

    OSZAR »
    Get the cheat sheet
    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Products

    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform

    Build

    • Developer Sandbox
    • Developer Tools
    • Interactive Tutorials
    • API Catalog

    Quicklinks

    • Learning Resources
    • E-books
    • Cheat Sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site Status Dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Report a website issue

    OSZAR »