Skip to main content
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 Red Hat 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

    • Red Hat OpenShift AI
    • 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.

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

    • 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.

ConsoleDocsSupport Search
New For you

Recommended

We'll recommend resources you may like as you browse. Try these suggestions for now.

  • Product downloads
  • Cheat sheets
  • Red Hat Developer learning portal
  • Developer blog
  • E-books
  • Developer Sandbox
Log in

Get more with a Red Hat Developer account

  • Product downloads
  • Console access
  • Event registration
  • Training & trials
Explore more account benefitsLog in or register

A subscription may be required for some services.

Contact us

Some more C# 9

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

    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

    • Run Red Hat Enterprise Linux CoreOS on NVIDIA BlueField DPUs

    • Agent harness engineering: Separating model capabilities from enforcement

    • What's new for developers in Red Hat Enterprise Linux 10.3 and 9.9

    • Control multicluster costs with right-sizing in Red Hat Advanced Cluster Management 5

    • Lightbits is now certified for Red Hat OpenStack Services on OpenShift

    Red Hat Developers logo

    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
    Ask AI