C# & CLR Internals (50 Qs)•Part 2: Concurrency, Zero-Allocation & Advanced Language Features (11 - 24)
What are ref struct, in parameters, and readonly struct in high-performance C#?
senior LevelCode ExampleFormsPerformance
In Simple Words:
ref struct: A value type that is strictly stack-allocated. It can never escape to the managed heap (cannot be boxed, cannot be a field of a class, cannot be used in async methods acrossawaitpoints). This enables types likeSpan<T>to safely point to stack memory.readonly struct: Informs the compiler that all fields are immutable, allowing the compiler to pass the struct by reference without creating defensive copies.inparameter: Passes a struct byreadonly refpointer rather than copying all struct bytes across stack frames.
csharp
public readonly ref struct StackBuffer {
public readonly ReadOnlySpan<byte> Data;
public StackBuffer(ReadOnlySpan<byte> data) => Data = data;
}