Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • Guided learning
      Receive custom learning paths powered by our AI assistant.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

C# 12: Collection expressions and primary constructors

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

    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

    • Trusted software factory: Building trust in the agentic AI era

    • Build a zero trust AI pipeline with OpenShift and RHEL CVMs

    • Red Hat Hardened Images: Top 5 benefits for software developers

    • How EvalHub manages two-layer Kubernetes control planes

    • Tekton joins the CNCF as an incubating project

    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. 

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

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    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
    © 2026 Red Hat

    Red Hat legal and privacy links

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

    Chat Support

    Please log in with your Red Hat account to access chat support.