C-Style Unions in C#
suggest changeUnion types are used in several languages, like C-language, to contain several different types which can “overlap”. In other words, they might contain different fields all of which start at the same memory offset, even when they might have different lengths and types. This has the benefit of both saving memory, and doing automatic conversion. Think of an IP address, as an example. Internally, an IPv4 address can be represented as an integer, but sometimes you want each byte, as in Byte1.Byte2.Byte3.Byte4. This works for value types, whether primitives such as int or long, or other structs you define. On a little-endian machine (including Windows), the field at offset 0 is the least significant byte.
We can achieve the same effect in C# by using Explicit Layout Structs.
using System;
using System.Runtime.InteropServices;
// The struct needs to be annotated as "Explicit Layout"
[StructLayout(LayoutKind.Explicit)]
struct IpAddress
{
// The "FieldOffset" means that this Integer starts, an offset in bytes.
// sizeof(int) == 4, sizeof(byte) == 1
[FieldOffset(0)] public int Address;
[FieldOffset(0)] public byte Byte1;
[FieldOffset(1)] public byte Byte2;
[FieldOffset(2)] public byte Byte3;
[FieldOffset(3)] public byte Byte4;
public IpAddress(int address) : this()
{
// When we init the Int, the Bytes will change too.
Address = address;
}
// Now we can use the explicit layout to access the
// bytes separately, without doing any conversion.
public override string ToString() => $"{Byte1}.{Byte2}.{Byte3}.{Byte4}";
}
Having defined the struct this way, you can use it as you would use a union in C. For example, create an address from a random integer and then set the first dotted component to 100, changing A.B.C.D to 100.B.C.D:
var ip = new IpAddress(new Random().Next());
Console.WriteLine($"{ip} = {ip.Address}");
ip.Byte1 = 100;
Console.WriteLine($"{ip} = {ip.Address}");
75.49.5.32 = 537211211
100.49.5.32 = 537211236