Skip to content

Instantly share code, notes, and snippets.

@jagt
Created June 6, 2018 04:16
Show Gist options
  • Save jagt/26e2b2b7cf86b61da6bb5a6377b6566a to your computer and use it in GitHub Desktop.
Save jagt/26e2b2b7cf86b61da6bb5a6377b6566a to your computer and use it in GitHub Desktop.
C# Union
using System;
using System.Runtime.InteropServices;
// turns out primitive C# union is already doable
// http://www.xtremedotnettalk.com/tutors-corner/97390-unions.html
[StructLayout(LayoutKind.Explicit)]
public struct MyUnion
{
[FieldOffset(0)]
public bool Bool;
[FieldOffset(0)]
public int Int;
[FieldOffset(0)]
public float Float;
public static MyUnion Instance;
static MyUnion()
{
Instance = new MyUnion();
// this duplicated initialize is necessary to make compiler happy, but it only happen once
Instance.Bool = false;
Instance.Int = 0;
Instance.Float = 0;
}
}
class Program
{
static void Main(string[] args)
{
MyUnion union = MyUnion.Instance;
union.Int = 1;
Console.Write(string.Format("union: bool:{0}, int:{1}, float:{2}", union.Bool, union.Int, union.Float));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment