The views expressed on this weblog are mine alone and do not necessarily reflect the views of my employer.
 Tuesday, January 28, 2003
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;
     }     

      class Class1
      {
            [STAThread]
            static void Main(string[] args)
            {
                  UnionTest u = new UnionTest();
                  // Set via Int and get through Char
                  u.intVal = 65;
                  Console.WriteLine("chVal:{0}",u.chVal );
                  // Set via Char and get through Int
                  u.chVal = 'B';
                  Console.WriteLine("intVal:{0}",u.intVal );
            }

Disclaimer
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.


Updated Link to this post 9:36:19 AM  #    comment []  trackback []