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

Some more C# 13

April 21, 2025
Tom Deseyn
Related topics:
.NETCompilers
Related products:
Developer Tools

Share:

    In the previous C# 13 article, you learned about features you’ll see in everyday code. In this final installment, we’ll take a look at the advanced features of the latest C# version, such as generic ref struct parameters, ref struct interfaces, the System.Threading.Lock type, and OverloadResolutionPriorityAttribute.

    Generic ref struct parameters

    Generic programming was introduced long before ref struct. The type parameters are assumed to be heap allocatable, therefore ref struct types could not be used.

    C# 13 is changing this. A new constraint, allows ref struct, enables you to indicate a generic type may be a ref struct. When this constraint is added, all operations performed on the type instances must be ref struct permitted.

    void Generic<T>()
    {
      var array = new T[2]; // allocates on heap
    }
    
    void GenericAllowsRefStruct<T>() where T : allows ref struct
    {
      // var array = new T[2]; // error: Array elements cannot be of type 'T'.
      T instance = default;
    }

    While the method implementation is constrained to use only ref struct compatible operations, it can be called with ref structs and non-ref structs. The following code shows calling this method with concrete types as well as generic parameters.

    void UseWithNonRefStruct()
      => GenericAllowsRefStruct<int>();
    
    void UseWithRefStruct()
      => GenericAllowsRefStruct<ReadOnlySpan<byte>>();
    
    static void UseWithNonRefGeneric<T>()
    {
      var array = new T[2]; // allocates on heap
      GenericAllowsRefStruct<T>();
    }
    
    void UseWithAllowsRefGeneric<T>() where T : allows ref struct
      => GenericAllowsRefStruct<T>();

    As shown by the previous UseWithNonRefGeneric example, when the method (or type) is used with a generic parameter, that parameter is not assumed to allow ref struct unless it is declared to be. In other words, the user of the generic method (or type) decides whether it wants to maintain the constraint.

    One use case for the allows ref struct generic constraint is to pass state arguments to methods which will be passed back to a callback delegate. Thanks to the allows ref struct, the state may now be ref struct (like a ReadOnlySpan). An example of such a method is string.Create, which is used to construct a string from some state. This is its signature:

    static string Create<TState>(int length, TState state, SpanAction<char, TState> action) where TState : allows ref struct

    Many .NET generic delegates have been updated with the constraint to enable passing and returning ref structs, including System.Action and System.Func.

    IEnumerable<T> and IAsyncEnumerable<T> include the constraint as well. This allows implementing specialized enumerables where T is a ref struct. Base class collection types, like List<T>, do not maintain the constraint when implementing the interface. This is expected since their storage is heap-based.

    ref struct interfaces

    As described in the previous section, ref struct types can now be used as generic parameter types. This doesn’t allow you to do much with these types, as the only thing that is known about the type is that it may be a ref struct. C# 13 also makes it possible for ref structs to implement interfaces. The ref structs can’t be casted to these interfaces (since that would require boxing them to the heap). The interfaces can be used as generic constraints, as shown in the next example.

    UseFoo(new MyRefStruct());
    UseFoo(new RegularStruct());
    
    void UseFoo<T>(T instance) where T : IFoo, allows ref struct
      => instance.Foo();
    
    interface IFoo
    {
      void Foo();
    }
    
    ref struct MyRefStruct : IFoo
    {
      public void Foo()
        => Console.WriteLine("MyRefStruct.Foo");
    }
    
    struct RegularStruct : IFoo
    {
      public void Foo()
        => Console.WriteLine("RegularStruct.Foo");
    }

    Lock type

    Any reference type instance can be used to implement mutual exclusive access via the lock keyword. This locking uses the .NET Monitor class under the hood. .NET 9 introduces a new dedicated lock type named System.Threading.Lock. Thanks to its specialized implementation, this lock performs better than the monitor-based locking (Performance Improvements in .NET 9 - Threading). The Lock type is recognized by the C# compiler and can be used with the C# lock statement.

    using System.Diagnostics;
    using System.Threading;
    
    Lock gate = new Lock();
    
    lock (gate)
    {
      Debug.Assert(gate.IsHeldByCurrentThread);
      Console.WriteLine("Called under lock");
    }

    The Lock type is a reference type. For the compiler to use the specialized locking (and not use monitor-based locking), the compiler must be aware of the type. If we change the gate declaration from Lock to object in the previous example, the compiler uses monitor-based locking. Fortunately, the compiler generates a CA9216 warning to inform us that we’re not using the specialized Lock implementation.

    Overload resolution priority

    The compiler can be told what method overloads are preferred using the new OverloadResolutionPriority attribute. This is useful in libraries where the existing method can’t be removed due to backwards compatibility, and a new overload is introduced that is preferable or that may create ambiguity with an existing member. The attribute takes an integer value for which higher values indicate a higher priority.

    The following example uses the OverloadResolutionPriority to prefer a new overload over an existing one that is an exact match with the caller argument type.

    using System.Runtime.CompilerServices;
    
    int[] numbers = new int[10];          // type is int[]
    int result = Calculator.Sum(numbers); // calls the ReadOnlySpan overload
    
    static class Calculator
    {
      public static int Sum(int[] array) { ... }
    
      [OverloadResolutionPriority(1)]
      public static int Sum(ReadOnlySpan<int> span) { ... }
    }

    New and improved C# 13

    In this final article of our two-part series, we looked at the advanced C# 13 features, such as generic ref struct parameters, ref struct interfaces, the System.Threading.Lock type and the OverloadResolutionPriorityAttribute. These new advanced features improve C# for specific use cases.

    Last updated: April 23, 2025

    Related Posts

    • Some more C# 12

    • C# 12: Collection expressions and primary constructors

    • .NET 9 now available for RHEL and OpenShift

    • Use compiler flags for stack protection in GCC and Clang

    Recent Posts

    • How to use RHEL 10 as a WSL Podman machine

    • MINC: Fast, local Kubernetes with Podman Desktop & MicroShift

    • How to stay informed with Red Hat status notifications

    • Getting started with RHEL on WSL

    • llm-d: Kubernetes-native distributed inferencing

    What’s up next?

    This cheat sheet covers the basics of installing .NET on Red Hat Enterprise Linux (RHEL), how to get a simple program running, and how to run a program in a Linux container.

    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