C# doesn’t have a direct keyword equivalent to C/C++ union, but you can achieve the same memory-overlap behavior using struct with explicit layout via StructLayout. In C/C++:
union Data {
int i;
float f;
};
Both fields share the same memory.
C# Equivalent
Use StructLayout(LayoutKind.Explicit) and FieldOffset:
using System;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit)]
struct Data
{
[FieldOffset(0)]
public int i;
[FieldOffset(0)]
public float f;
}
Example Usage
class Program
{
static void Main()
{
Data d = new Data();
d.i = 1065353216; // Bit pattern for float 1.0
Console.WriteLine(d.f); // Outputs: 1
d.f = 2.5f;
Console.WriteLine(d.i); // Shows underlying int bits
}
}
Key Points
• LayoutKind.Explicit → lets you control memory layout manually
• FieldOffset(0) → forces fields to overlap (like a union)
• Works only with structs, not classes
• Commonly used for:
- Interop with native code
- Bit-level manipulation
- Performance-sensitive scenarios
Important Warnings
• Not type-safe — you’re interpreting raw memory
• Can lead to hard-to-debug issues if misused
• Be careful with:
- reference types (generally avoid them here)
- different field sizes and alignment
Alternative (Safer Approach)
If you just want similar behavior (not memory overlap), consider:
class Data
{
public int? IntValue;
public float? FloatValue;
}
Or use object, or better yet a discriminated pattern (like enums + fields).
When to use real “union-style” in C#?
Use explicit layout only when:
• You need binary compatibility (interop, file formats)
• You’re doing low-level memory tricks
Otherwise, it’s usually better to stick with safe, idiomatic C# designs.
One thing to be careful of is the endian-ness of the machine if you plan to run it on non-x86 platforms that may have differing endianness.
See http://en.wikipedia.org/wiki/Endianness for an explanation.