What is Union in C#?Explain with sample code

One can simulate union in C# with the help of StructLayout and FieldOffset attributes.

StructLayout attribute allows the user to control the physical layout of the data fields of a class or structure. Specify the LayoutKind the first parameter as LayoutKind.Explicit.

Tag each field with FieldOffset attribute. The attribute must be applied so that the type members are overlaying the same memory area.


using System;
using System.Runtime.InteropServices;
// Above namespace required for StructLayout attribute
namespace UnionTest
{
class Program
{
static void Main(string[] args)
{
Union test = new Union();
test.x = 256;
//Setting value 256 makes high-order byte to be set to 1. Byte ranges up to 255.
Console.WriteLine("Low:" + test.lowx + "\nHigh:" + test.highx);
}
}
[StructLayout(LayoutKind.Explicit,Size=2)]
public struct Union
{
//2 bytes
[FieldOffset(0)]public short x;
//1 byte
[FieldOffset(0)]public byte lowx;
//1 byte -->represents high-order byte.
[FieldOffset(1)]public byte highx;
}
}

No comments:

Post a Comment