EN CSharp Keyword unmanaged generic type constraint - LIHACHTETAN/ClassicUO-Bad-Newbie-CSharp-Scripts-IDE GitHub Wiki

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

C#: unmanaged — type parameter limit

Handbook C# · Practical Guide

The where T : unmanaged constraint allows only value types without managed references in their composition. It allows you to use sizeof(T) and T* in an allowed unsafe context. This is a type constraint, not a function call convention. It is not combined with separate struct or new().

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
int Size<T>() where T : unmanaged
{
    unsafe { return sizeof(T); }
}
System.Console.WriteLine(Size<int>());

Result:

4

Syntax

static int ByteSize<T>() where T : unmanaged;
static void Swap<T>(T* left, T* right) where T : unmanaged;

The size of a simple type and structure without references

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;

public struct GridPoint { public int X; public int Y; }
internal static unsafe class Program
{
    public static void Main()
    {
        Console.WriteLine(ByteSize<int>());
        Console.WriteLine(ByteSize<GridPoint>());
    }
    private static int ByteSize<T>() where T : unmanaged => sizeof(T);
}

Result:

4
8

Generalized exchange of values ​​​​through pointers

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()
    {
        int left = 10;
        int right = 25;
        Swap(&left, &right);
        Console.WriteLine($"{left},{right}");
    }
    private static void Swap<T>(T* left, T* right) where T : unmanaged
    {
        T temporary = *left;
        *left = *right;
        *right = temporary;
    }
}

Result:

25,10

Official source: Microsoft Learn.

⚠️ **GitHub.com Fallback** ⚠️