Create a C-style union

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
C# Code Snippets

C# Source Code Bank

See also …
edit

This Visual C# code snippet uses the ExplicitLayout attribute to layout a struct explicitly and create a C-style union.

using System.Runtime.InteropServices;
...
[StructLayout(LayoutKind.Explicit)]
internal struct Union
{
   [FieldOffset (6)] internal byte byteData;
   [FieldOffset (0)] internal string stringText;
   [FieldOffset (4)] internal short unionShort;
   [FieldOffset (4)] internal byte lowByte;
   [FieldOffset (5)] internal byte highByte;
}
 
public class TestUnion
{
   public static void Main( )
   {
      Union union = new Union ();
      union.stringText = "Union";
      union.byteData   = 0xFF;
      union.lowByte    = 0x01;
      union.highByte   = 0x01;
      Console.WriteLine (union.unionShort + " = " + 
         (union.highByte * 256 + union.lowByte).ToString());
   }			
}

Today's Deals: Electronics

Personal tools