ref struct types - C# reference (original) (raw)

You can use the ref modifier in the declaration of a structure type. Instances of a ref struct type are allocated on the stack and can't escape to the managed heap. To ensure that, the compiler limits the usage of ref struct types as follows:

Typically, you define a ref struct type when you need a type that also includes data members of ref struct types:

public ref struct CustomRef
{
    public bool IsValid;
    public Span<int> Inputs;
    public Span<int> Outputs;
}

To declare a ref struct as readonly, combine the readonly and ref modifiers in the type declaration (the readonly modifier must come before the ref modifier):

public readonly ref struct ConversionRequest
{
    public ConversionRequest(double rate, ReadOnlySpan<double> values)
    {
        Rate = rate;
        Values = values;
    }

    public double Rate { get; }
    public ReadOnlySpan<double> Values { get; }
}

In .NET, examples of a ref struct are System.Span and System.ReadOnlySpan.

ref fields

Beginning with C# 11, you can declare a ref field in a ref struct, as the following example shows:

public ref struct RefFieldExample
{
    private ref int number;

    public int GetNumber()
    {
        if (System.Runtime.CompilerServices.Unsafe.IsNullRef(ref number))
        {
            throw new InvalidOperationException("The number ref field is not initialized.");
        }

        return number;
    }
}

A ref field can have the null value. Use the Unsafe.IsNullRef(T) method to determine if a ref field is null.

You can apply the readonly modifier to a ref field in the following ways:

The compiler ensures that a reference stored in a ref field doesn't outlive its referent.

The ref fields feature enables a safe implementation of types like System.Span:

public readonly ref struct Span<T>
{
    internal readonly ref T _reference;
    private readonly int _length;

    // Omitted for brevity...
}

The Span<T> type stores a reference through which it accesses the contiguous elements in memory. The use of a reference enables a Span<T> instance to avoid copying the storage it refers to.

The disposable pattern

You can define a disposable ref struct. To do that, ensure that a ref struct fits the disposable pattern. That is, it has an instance Dispose method, which is accessible, parameterless and has a void return type. You can use the using statement or declaration with an instance of a disposable ref struct.

Beginning with C# 13, you can also implement the IDisposable on ref struct types. However, overload resolution prefers the disposable pattern to the interface method. The compiler resolves to an IDisposable.Dispose method only when a suitable Dispose method isn't found.

Restrictions for ref struct types that implement an interface

These restrictions ensure that a ref struct type that implements an interface obeys the necessary ref safety rules.

The compiler enforces these restrictions. If you write ref struct types that implement interfaces, each new update might include new default interface members. Until you provide an implementation for any new instance methods, your application won't compile. You can't provide a specific implementation for a static interface method with a default implementation.

Important

A ref struct that implements an interface includes the potential for later source-breaking and binary-breaking changes. The break occurs if a ref struct implements an interface defined in another assembly, and that assembly provides an update which adds default members to that interface.

The source-break happens when you recompile the ref struct: It must implement the new member, even though there's a default implementation.

The binary-break happens if you upgrade the external assembly without recompiling the ref struct type and the updated code calls the default implementation of the new method. The runtime throws an exception when the default member is accessed.

C# language specification

For more information, see the following sections of the C# language specification:

For more information about ref fields, see the Low-level struct improvements proposal note.

See also