2y ago · Jun 28, 2024 2:25 PM
In C/C++, unions allow multiple variables to share the exact same memory location. In C#, you can achieve the exact same behavior using !
Example: Fast 32-bit Color Converter Union
CODE
[StructLayout(LayoutKind.Explicit)]Example: Fast 32-bit Color Converter Union
CSHARP
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit)]
public struct Color32Union
{
// Raw 32-bit unsigned integer (ARGB)
[FieldOffset(0)] public uint RawValue;
// Individual 8-bit color channels sharing the same 4 bytes!
[FieldOffset(0)] public byte B;
[FieldOffset(1)] public byte G;
[FieldOffset(2)] public byte R;
[FieldOffset(3)] public byte A;
}
// Usage:
Color32Union col = default;
col.RawValue = 0xFF1084FF; // Set as 32-bit hex
Console.WriteLine($"R: {col.R}, G: {col.G}, B: {col.B}, A: {col.A}");
// Modifying blue channel updates the raw uint instantly with zero bit shifts!
col.B = 0x00;
StructAligner · Data-Oriented Design
Structure of Arrays (SoA) vs Array of Structures (AoS) for m...
Structure of Arrays (SoA) vs Array of Structures (AoS) for m...
The following users thanked StructAligner for this post: