DEV Community

Cover image for C# - Function Pointers for High-Performance Scenarios
Keyur Ramoliya
Keyur Ramoliya

Posted on

C# - Function Pointers for High-Performance Scenarios

C# 9.0 introduced function pointers as a new feature, offering a way to work with pointers to functions in a manner similar to C and C++. This is particularly useful in performance-critical applications where you need to avoid the overhead associated with delegates, such as interop scenarios or low-level system programming.

Here’s how to use function pointers in C#:

  1. Declare Function Pointers:
    Use the delegate* syntax to declare a function pointer. You can specify the calling convention and the parameter and return types.

  2. Use in High-Performance Code:
    Function pointers can be used in places where delegates would traditionally be used, but where the overhead of a delegate is undesirable.


using System;
using System.Runtime.InteropServices;

class Program
    // Declaring a function pointer type
    static unsafe delegate*<int, int, int> addPtr;

    static void Main()
            // Assigning a method to the function pointer
            addPtr = &Add;
            int result = addPtr(3, 5);
            Console.WriteLine($"Result: {result}");

    // Method compatible with the function pointer
    static int Add(int x, int y)
        return x + y;
Enter fullscreen mode Exit fullscreen mode

In this example, addPtr is a function pointer that points to the Add method. This setup avoids the overhead of delegates, which can be beneficial in certain high-performance scenarios.

Function pointers in C# are an advanced feature and should be used with caution, as they introduce unsafe code into your application. They are best suited for scenarios where performance is critical and where the developer has a good understanding of pointers and low-level programming concepts.

Top comments (0)