C# Union
By FoxLearn 12/27/2024 2:40:41 AM 189
However, only one member can be accessed at a time. For instance, consider a C/C++ union that can be used to store either 2 floating-point numbers or a single long integer.
union MyUnion { float f[2]; long l; };
C# does not directly support the C/C++ style union. However, we can replicate this behavior using the Explicit
StructLayout
attribute. By specifying StructLayout(LayoutKind.Explicit)
and using FieldOffset
to define the memory offsets, we can create a similar structure in C#.
To create a union-like structure in C#, follow these steps:
- Specify the
StructLayout
attribute with theLayoutKind.Explicit
option. - Use the
FieldOffset
attribute to define the memory offset for each field.
using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Explicit)] public struct MyUnion { [FieldOffset(0)] public float f1; [FieldOffset(4)] public float f2; [FieldOffset(0)] public long l; } class Program { static void Main(string[] args) { MyUnion u = new MyUnion(); u.l = 1234567890123456789L; Console.WriteLine("Long value: {0}", u.l); Console.WriteLine("First float: {0}, Second float: {1}", u.f1, u.f2); } }
In this example:
- The
MyUnion
struct in C# is defined with twofloat
values (f1
andf2
) and onelong
value (l
). - The
FieldOffset(0)
for bothf1
andl
indicates that they share the same memory location. - The
FieldOffset(4)
forf2
ensures it starts afterf1
, as afloat
typically occupies 4 bytes.
When the l
field is set, it affects the f1
and f2
fields due to the shared memory space, similar to how C/C++ unions operate. When you print f1
and f2
, the values may not correspond to floating-point representations of l
, since the raw memory is being interpreted in different ways.
- How to use JsonConverterFactory in C#
- How to serialize non-public properties using System.Text.Json
- The JSON value could not be converted to System.DateTime
- Try/finally with no catch block in C#
- Parsing a DateTime from a string in C#
- Async/Await with a Func delegate in C#
- How to batch read with Threading.ChannelReader in C#
- How to ignore JSON deserialization errors in C#