How can I implement C/C++ "union" in C#?

How can I implement C/C++ "union" in C#?

C# doesn't natively support the C/C++ notion of unions. However, you can use the StructLayout(LayoutKind.Explicit) and FieldOffset attributes to create equivalent functionality. Try the given code below:

using System.Runtime.InteropServices;

struct Data {
  public byte Byte1;
  public byte Byte2;
  public byte Byte3;
  public byte Byte4;
  public byte Byte5;
  public byte Byte6;
  public byte Byte7;
  public byte Byte8;
  public int Int1;
  public int Int2;

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 for an explanation.

How can I implement C/C++
added 8 years 2 months ago

- Open a text file and read line by line in C#
- Convert.ToInt32() vs Int32.Parse() in C#
- How to C# Linq Group By by paramater/field names
- Simple Injector
- How to check memory consumption in c#
- How can I implement C/C++ "union" in C#?
- How to Open and Read From Excel File in C#
- Weak References
- Lazy Initialization
- Enable Nuget Package Restore
- OnixS FIX Engine
- Rapid Addition FIX API
- How to change DateTime format in C#
- How to change number decimal seperator in C#?