csharp / expert
Snippet
Explicit Struct Layouts for Memory Overlays
In expert performance tuning, LayoutKind.Explicit allows developers to control the exact memory offset of fields. This creates C-style 'unions' where multiple fields share the same memory location, enabling high-performance type reinterpretation without allocations.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System.Runtime.InteropServices;[StructLayout(LayoutKind.Explicit)]public struct ValueUnion{[FieldOffset(0)]public int IntegerVal;[FieldOffset(0)]public float FloatVal;[FieldOffset(0)]public byte ByteVal;}// Usagevar union = new ValueUnion { IntegerVal = 42 };Console.WriteLine(union.FloatVal); // Reinterprets the same 4 bytes as a float
Breakdown
1
[StructLayout(LayoutKind.Explicit)]
Instructs the runtime that field positions are manually defined via offsets.
2
[FieldOffset(0)]
Places the field at the very beginning of the struct memory block, causing overlap.