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;

[StructLayout(LayoutKind.Explicit)]
struct Data {
  [FieldOffset(0)]
  public byte Byte1;
  [FieldOffset(1)]
  public byte Byte2;
  [FieldOffset(2)]
  public byte Byte3;
  [FieldOffset(3)]
  public byte Byte4;
  [FieldOffset(4)]
  public byte Byte5;
  [FieldOffset(5)]
  public byte Byte6;
  [FieldOffset(6)]
  public byte Byte7;
  [FieldOffset(7)]
  public byte Byte8;
  [FieldOffset(0)]
  public int Int1;
  [FieldOffset(4)]
  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 http://en.wikipedia.org/wiki/Endianness for an explanation.


How can I implement C/C++
added 9 years 4 months ago

- How to POST and GET url with parameters in C#?
- 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#?
2
1