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# 9

April 27, 2021
Tom Deseyn
Related topics:
.NET
Related products:
Developer Tools

Share:

    In this final article of our C# 9 series, we’ll look at advanced features related to native interop and performance in C# 9.

    If you missed any of the previous articles in this series, here's where you can catch up:

    • Part 1: C# 9 top-level programs and target-typed expressions
    • Part 2: C# 9 pattern matching
    • Part 3: C# 9 new features for methods and functions
    • Part 4: C# 9 init accessors and records

    Native-sized integers

    C# 9 introduces language support for native-sized integer types, both signed and unsigned. The existing C# int and long types, which map to the underlying System.Int32 and System.Int64 types, have a fixed size of 32 bits and 64 bits, respectively. The new nint and nuint types, which map to the existing System.IntPtr and System.UIntPtr types, have a size that corresponds to the native machine size. That means they are 32 bit on a 32-bit machine and 64 bit on a 64-bit machine.

    C# supports direct arithmetic on nint and nuint:

    // IntPtr aren't directly usable for arithmetic.
    IntPtr a = (IntPtr)5;
    IntPtr b = (IntPtr)6;
    IntPtr c = new IntPtr((long)a + (long)b);
     
    // nint/nuint can be used for arithmetic.
    nint i = 5;
    nint j = 6;
    nint k = i + j;
     
    // cast required: int-size may be smaller.
    int y = (int)i;
    

    Native integers can be marked const, but only when the compiler knows that the result won’t overflow on any architecture:

    const nint n = int.MaxValue;
    // error CS0133: The expression being assigned to 'm' must be constant.
    const nint m = unchecked(n + 1);
    

    Native libraries often use machine-sized native integers in their APIs, and the new nint/nuint facilitate using such APIs from .NET:

    public unsafe int write(int fd, Span buffer)
    {
     fixed(byte* buf = buffer)
     {
       return (int)write(fd, buf, (nuint)buffer.Length);
     }
     // ssize_t write(int fd, const void *buf, size_t count);
     //   ssize_t, and size_t are signed/unsigned native-size integer types.
     [DllImport("libc", SetLastError = true)]
     static extern nint write(int fd, void* buf, nuint count);
    }
    

    Suppressing localsinit

    The localsinit feature can improve performance. To understand it, have a look at the following method:

    void ReadData()
    {
       Span buffer = stackalloc byte[256];
       int bytesRead = Read(buffer);
       buffer = buffer.Slice(0, bytesRead);
       ProcessData(buffer);
    }
    

    Each time this method is called, the runtime ensures that the allocated buffer is zeroed so that the method won't read uninitialized data from the stack. The C# compiler emits the .locals init directive in the method for this to happen.

    When performance is critical, it may be desirable to omit this zeroing. C# 9 supports that performance measure through the new SkipLocalsInit attribute. This attribute can be applied at the method level, the class level, or even for the entire module:

    // For the entire project.
    [module: System.Runtime.CompilerServices.SkipLocalsInit]
     
    // or, for a  specific method.
    [SkipLocalsInit]
    void ReadData()
    {
       // ...
    

    If you add this attribute, be careful to initialize variables that are used as out parameters or whose addresses you pass to another function. Those variables will no longer be zeroed by the compiler:

    [SkipLocalsInit]
    unsafe void Foo()
    {
       int i; // i is not cleared.
       Bar(&i);
    }
    

    Module initializers

    C# supports static type constructors, which get called only once when the type is first used. C# 9 makes it possible to add a constructor at the assembly level (more specific: module level). This module initializer runs one time when the module is first used.

    Compared to static constructors, a module initializer is more efficient because the runtime doesn’t have to track whether the constructor has been called for each type. Additionally, a module initializer avoids ordering issues that may exist between multiple static constructors.

    A method can be marked as a module initializer by adding the ModuleInitializer attribute. The method must be public or internal, have a void return type, and must not accept parameters:

    static void Main(string[] args)
    {
       Console.WriteLine("Hello from Main.");
    }
    
    [ModuleInitializer]
    static internal void MyInitializer()
    {
        Console.WriteLine("Hello from initializer!");
    }
    

    Multiple methods can have the ModuleInitializer attribute. The compiler generates a module initializer that calls all of them.

    Function pointers

    C# has always supported passing methods using delegates. Delegates are reference types and refer to one or more methods that can be invoked through the delegate:

    Action<string> myDelegate = s => Console.WriteLine($"Hello 1 {s}");
    myDelegate += s => Console.WriteLine($"Hello 2 {s}");
    myDelegate("world!");
    

    C# 9 goes a level deeper and allows you to use function pointers directly in C#. Function pointers contain just the address of the function. They may only be used in unsafe blocks.

    Function pointers can refer to managed static methods or native functions. For native functions, you can further specify the calling convention if the default is not appropriate. This tells the JIT how arguments need to be passed to the function.

    Function pointers are declared using delegate*. The next example declares three function pointers:

    var pFun1 = (delegate* unmanaged<int, void>)NativeLibrary.GetExport(libHandle, "fun1");
    
    var pFun2 = (delegate* unmanaged[Stdcall]<int, void>)NativeLibrary.GetExport(libHandle, "fun2");
    
    delegate*<int, void> pManagedFunction = &ManagedFunction;
    

    The first two pointers are unmanaged and initialized using the NativeLibrary class. The type parameters are the same as for the Func delegate: first the argument types, and finally the return type. The pointers declared here accept an int and have no return type (void).

    The second function pointer specifies the Stdcall calling convention to change from the platform default.

    The third function pointer is a managed function pointer. It is assigned using the address-of operator on a static method.

    Function calls can be made using the expected call syntax:

    pManagedFunction(10);
    

    A special case is passing the address of a managed method to a native library. For this, we need to add the UnmanagedCallersOnly attribute to the method. This tells the runtime the method will be called from native code. Such methods must not be called from managed code and can have only blittable arguments:

    [UnmanagedCallersOnly]
    static void Log(IntPtr ptr)
    {
      Console.Write(Marshal.PtrToStringAnsi(ptr));
    }
    
    static unsafe void Main(string[] args)
    {
      delegate* unmanaged<IntPtr, void> pLog = &Log;
      nativelib_set_log_function(pLog);
      ...
    }
    

    Conclusion

    In this article, we looked at the new nint and nuint native-sized integer types and how they facilitate interop. We learned how the SkipLocalsInit attribute can avoid the cost of zeroing stack locals. We covered how module initializers allow you to run one or more methods when an assembly or module is first used. And finally, we looked at function pointers and how they can be used with managed and unmanaged functions.

    C# 9 can be used with the .NET 5 SDK, which is available on Red Hat Enterprise Linux, Red Hat OpenShift, Fedora, Windows, macOS, and other Linux distributions. For more information on Red Hat's support for .NET, see the Red Hat Developer .NET topic page.

    Last updated: February 5, 2024

    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

    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