Skip to content

EN CSharp Keyword allows

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: allows

Handbook C# · Practical Guide

The allows ref struct antirestriction allows you to pass a ref struct as an argument to a generic type or method. It does not require that each argument be a ref struct. Code with such a T must follow the rules of link safety and cannot perform boxing. Anti-restrictions are written after other restrictions.

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
void Ignore<T>(T value) where T : allows ref struct { }
System.Span<int> values = stackalloc int[2];
Ignore(values);
System.Console.WriteLine(values.Length);

Result:

2

Syntax

static int Measure<T>(T value) where T : IMeasured, allows ref struct;
static void Reset<T>(scoped ref T value) where T : allows ref struct;

Interface contract for ref struct without boxing

using System;

public interface IMeasured { int Length { get; } }
public readonly ref struct NumberView : IMeasured
{
    private readonly ReadOnlySpan<int> values;
    public NumberView(ReadOnlySpan<int> values) => this.values = values;
    public int Length => values.Length;
}
internal static class Program
{
    public static void Main()
    {
        ReadOnlySpan<int> values = stackalloc int[] { 4, 8, 15 };
        var view = new NumberView(values);
        Console.WriteLine(Measure(view));
    }
    private static int Measure<T>(T value) where T : IMeasured, allows ref struct
        => value.Length;
}

Result:

3

One reset function for Span and regular number

using System;

internal static class Program
{
    public static void Main()
    {
        Span<int> scratch = stackalloc int[] { 1, 2, 3 };
        int counter = 7;
        Reset(ref scratch);
        Reset(ref counter);
        Console.WriteLine($"Span length: {scratch.Length}; counter: {counter}");
    }
    private static void Reset<T>(scoped ref T value) where T : allows ref struct
        => value = default!;
}

Result:

Span length: 0; counter: 0

Official source: Microsoft Learn.

Clone this wiki locally