Scott Hanselman

Unions (or an equivalent) in C# - Sairama's Tip of the Day

January 28, '03 Comments [0] Posted in Web Services
Sponsored By

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.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb
Comments are closed.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.