csharp / expert
Snippet
Memory-Efficient Variant Implementation
At an expert level, C# allows for low-level memory management using `StructLayout`. An explicit layout enables multiple fields to overlap in memory, effectively creating a 'Union' similar to C++. This is critical for high-performance scenarios where memory footprint must be minimized for large collections of polymorphic data types.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System.Runtime.InteropServices;[StructLayout(LayoutKind.Explicit)]public struct TaggedUnion{[FieldOffset(0)] public byte TypeIndicator;// Both fields share the same memory location (offset 1)[FieldOffset(1)] public int IntegerValue;[FieldOffset(1)] public float FloatValue;public static TaggedUnion FromInt(int val) =>new TaggedUnion { TypeIndicator = 0, IntegerValue = val };public static TaggedUnion FromFloat(float val) =>new TaggedUnion { TypeIndicator = 1, FloatValue = val };}
Breakdown
1
[StructLayout(LayoutKind.Explicit)]
Tells the runtime that field positions will be manually defined rather than automatically calculated.
2
[FieldOffset(1)]
Specifies the exact byte position where the field starts, allowing different types to occupy the same memory slots.