Unions (or an equivalent) in C# - Sairama's Tip of the Day
Someone needed "union" functionality in C# and Sairama came up with this creative and possible heretical use of Interop Attributes.
[ StructLayout(LayoutKind.Explicit) ]
public struct UnionTest
// Set the offsets to the same position so that both variables occupy
// the same memory address which is essentially C++ union does.
[ FieldOffset(0) ] public char chVal;
[ FieldOffset(0) ] public System.Int16 intVal;
static void Main(string args)
UnionTest u = new UnionTest();
// Set via Int and get through Char
u.intVal = 65;
// Set via Char and get through Int
u.chVal = 'B';
The code above shows only features of .NET and in no way suggest/dictates/advises usage. Don't be lame and think this is source code you can actually do something with.