skip to content

In C#, what does `where T : unmanaged` guarantee that `where T : struct` does not, when copying rows into a byte buffer?

level: middleimportance: should knowfreq 40%

answer

  1. a value type can still hold references
  2. fields at every nesting level
  3. stackalloc and raw bytes
  4. CS8377 vs ArgumentException

basics

~20 s

struct only promises a non-nullable value type, which may still contain references such as a string field. unmanaged also requires every field, at any depth, to be unmanaged, so stackalloc T[n] compiles and a string-holding row fails with CS8377.

solid answer

~40 s

`where T : struct` admits any non-nullable value type, including one with a `string` or array field. `where T : unmanaged` admits only types that are plain bytes all the way down: the numeric types, `char`, `bool`, enums, pointers, and structs whose fields are all unmanaged. `MemoryMarshal.AsBytes<T>(Span<T>)` is declared `where T : struct` and checks `RuntimeHelpers.IsReferenceOrContainsReferences<T>()` when it runs, throwing `ArgumentException` for a row with a reference. Wrapping it in a method constrained to `unmanaged` moves that failure to compile time as CS8377. Inside the body, `unmanaged` also allows `Span<T> s = stackalloc T[n]` (CS0208 under `struct`). It does not make `sizeof(T)` safe code: that still needs an `unsafe` context (CS0233).

code

csharp · 29 lines
csharp
using System.Runtime.InteropServices;

PriceRow[] rows = [new(1, 9.5), new(2, 12.25)];
Span<byte> bytes = RowCopier.ToBytes<PriceRow>(rows);
Console.WriteLine($"{bytes.Length} bytes for {rows.Length} rows");

try
{
    LabelRow[] labels = [new(1, "apple")];
    RowCopier.ToBytesLoose<LabelRow>(labels);
}
catch (ArgumentException ex)
{
    Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
}

static class RowCopier
{
    // unmanaged: a row holding a reference is rejected at compile time (CS8377)
    public static Span<byte> ToBytes<T>(Span<T> rows) where T : unmanaged
        => MemoryMarshal.AsBytes(rows);

    // struct only: the same mistake compiles and fails when it runs
    public static Span<byte> ToBytesLoose<T>(Span<T> rows) where T : struct
        => MemoryMarshal.AsBytes(rows);
}

readonly record struct PriceRow(int Id, double Price);
readonly record struct LabelRow(int Id, string Label);

go deeper

for a junior

Recall that struct means a non-nullable value type and unmanaged means a value type with no references inside it at any depth.

for a middle

Explain what each unlocks: stackalloc T[n] and clean pointer use under unmanaged, CS8377 for a struct with a string field, and that sizeof(T) still needs unsafe.

for a senior

Show the production value: an API declared only where T : struct, like MemoryMarshal.AsBytes, fails at run time with ArgumentException; an unmanaged wrapper moves that to compile time.

for a principal

Weigh exposing unmanaged in public generic APIs: it narrows who can call them but makes the memory-layout assumption explicit and stops a whole class of run-time failures.

## Two different promises Both constraints say "value type", but they promise different things about what is inside it: - `where T : struct` accepts any **non-nullable value type**: `int`, `DateTime`, a `record struct`, and also a struct with a `string` field or an `int[]` field. Those fields are references to objects on the managed heap, which the garbage collector tracks. - `where T : unmanaged` accepts only an **unmanaged type**: one with no references at any depth. The C# reference lists them: `sbyte`, `byte`, `short`, `ushort`, `int`, `uint`, `long`, `ulong`, `nint`, `nuint`, `char`, `float`, `double`, `decimal`, `bool`, any enum, any pointer type, tuples of unmanaged members, and user-defined structs whose fields are all unmanaged. A constructed generic struct counts too, so `Coords<int>` is unmanaged while `Coords<object>` is not. `unmanaged` implies `struct`, so the two cannot be written together (CS0449), and since `struct` implies `new()`, `unmanaged, new()` is rejected as well (CS8375). ## Where the difference bites: rows into bytes Consider a persistence helper that copies fixed-size rows into a byte buffer. `MemoryMarshal.AsBytes<T>(Span<T>)` does the reinterpretation, and its declaration in the .NET source is only `where T : struct`. The body then checks the type when it runs: ```csharp if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); ``` So a row holding a `string` compiles and then throws `ArgumentException` ("Cannot use type 'LabelRow'. Only value types without pointers or references are supported."). The check has to exist: copying a reference as bytes would hand out a raw heap address that the garbage collector may move. Wrap the call in your own method constrained to `unmanaged` and the same mistake never builds: ```csharp public static Span<byte> ToBytes<T>(Span<T> rows) where T : unmanaged => MemoryMarshal.AsBytes(rows); ``` Passing a `LabelRow(int Id, string Label)` now fails with **CS8377**: "The type 'LabelRow' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'RowCopier.ToBytes<T>(Span<T>)'". ## What `unmanaged` unlocks inside the body | Operation on `T` | under `struct` | under `unmanaged` | |---|---|---| | `Span<T> s = stackalloc T[n];` | CS0208 | compiles, in safe code | | `sizeof(T)` in safe code | CS0233 | CS0233 (still needs `unsafe`) | | `sizeof(T)`, `T*`, `&value` in an `unsafe` context | compiles with warning CS8500 | compiles cleanly | | passing to an API that requires `unmanaged` | not allowed | allowed | | `T?` as `Nullable<T>` | yes | yes | Two points in that table surprise people: 1. **`unmanaged` is not a licence for safe-code `sizeof`.** `sizeof` of a type parameter needs an `unsafe` context even when `T` is unmanaged. In safe code, `Unsafe.SizeOf<T>()` returns the size for any `T`. 2. **Pointers to `struct`-constrained `T` are a warning, not an error,** on today's compiler: CS8500, "This takes the address of, gets the size of, or declares a pointer to a managed type". The warning exists because such a `T` may contain references, and a raw pointer to them is not tracked by the garbage collector. ## Choosing between them - Use `struct` when you only need value semantics: `Nullable<T>`, avoiding `null`, or calling something declared `where T : struct`. - Use `unmanaged` when the code treats `T` as a block of memory: byte reinterpretation, `stackalloc`, pointers, native interop buffers. The constraint documents the assumption and turns a run-time `ArgumentException` into a compile-time CS8377 for every caller. - Keep in mind that `unmanaged` says nothing about layout or padding. A `record struct PriceRow(int Id, double Price)` is unmanaged and takes 16 bytes, not 12, because the `double` is aligned after the `int`; byte-level formats still have to account for that. ## A quick test for a type To decide by hand whether a struct is unmanaged, walk its fields: 1. a field of a primitive numeric type, `char`, `bool`, an enum or a pointer is fine; 2. a field of another struct type means repeating the walk inside that struct; 3. any field of a class, interface, delegate, array or `string` type makes the whole struct managed. Auto-properties count through their hidden backing fields, so a positional `record struct` with a `string` parameter is managed exactly like a struct with a `string` field.

  • Does `where T : unmanaged` make `sizeof(T)` legal in C# safe code?
    No. `sizeof` of a type parameter is CS0233 outside an `unsafe` context, with or without `unmanaged`. What `unmanaged` adds in safe code is `stackalloc T[n]` into a `Span<T>`. When you need a size in safe code, `Unsafe.SizeOf<T>()` works for any type argument, with no constraint at all.
  • In C#, is a generic struct such as `Coords<T>` an unmanaged type?
    It depends on the type argument, since C# 8: `Coords<int>` has only unmanaged fields and satisfies `where T : unmanaged`, while `Coords<object>` holds a reference and fails with CS8377. If every construction must be unmanaged, put `where T : unmanaged` on `Coords<T>` itself.

  • where T : struct already guarantees the type contains no reference fields.
  • unmanaged is simply struct plus new(), written in one word.
  • where T : unmanaged makes sizeof(T) and pointers usable without an unsafe context.
  • A struct with a string field is unmanaged because the struct itself is a value type.
  • MemoryMarshal.AsBytes rejects reference-holding structs at compile time.