Skip to content

EN CSharp Keyword managed function pointer calling convention

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

C#: managed — function pointer call convention

Handbook C# · Practical Guide

managed in the delegate* type specifies a managed call agreement; this is also the default option. The address is obtained by the & operator from the static method. Pointer declarations and calls are executed in an unsafe context; the project must allow unsafe blocks. A function pointer is not a delegate object.

Simple example (Example.cs)

Save this example separately as Example.cs. Run it independently of the other examples on this page.

Example.cs:

// PROJECT-EXAMPLE
unsafe
{
    delegate* managed<int, int> twice = &Twice;
    System.Console.WriteLine(twice(4));
}
static int Twice(int value) => value * 2;

Enable <AllowUnsafeBlocks>true</AllowUnsafeBlocks> in the project. The pointer is valid only within the shown scope.

Result:

8

Syntax

delegate* managed<int, int> operation = &Transform;

The address of the static method for calculating the square

File Example.csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <LangVersion>14.0</LangVersion>
    <Nullable>enable</Nullable>
    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
  </PropertyGroup>

</Project>

File Program.cs:

using System;

internal static unsafe class Program
{
    public static void Main()
    {
        delegate* managed<int, int> square = &Square;
        Console.WriteLine(square(7));
    }
    private static int Square(int value) => value * value;
}

Result:

49

Passing the selected operation to another method

File Example.csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <LangVersion>14.0</LangVersion>
    <Nullable>enable</Nullable>
    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
  </PropertyGroup>

</Project>

File Program.cs:

using System;

internal static unsafe class Program
{
    public static void Main()
    {
        delegate* managed<int, int, int> combine = &Add;
        Console.WriteLine(Apply(combine, 8, 3));
        combine = &Subtract;
        Console.WriteLine(Apply(combine, 8, 3));
    }
    private static int Apply(delegate* managed<int, int, int> operation, int left, int right)
        => operation(left, right);
    private static int Add(int left, int right) => left + right;
    private static int Subtract(int left, int right) => left - right;
}

Result:

11
5

Official source: Microsoft Learn.

Clone this wiki locally