Scott Hanselman

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

January 28, 2003 Comment on this post [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 bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

Comments are closed.

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