Skip to main content
InterviewHubPRO
Section Overview
Q13

Question 13 of 50

Part 2: Concurrency, Zero-Allocation & Advanced Language Features (11 - 24)

26%
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 across await points). This enables types like Span<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.
  • in parameter: Passes a struct by readonly ref pointer 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;
}