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;
}
}
3 comments:
Thanks Paddy
A Good One......
Hey Pradip,Good Posts
Would be a great help if Ajax in ASP.NET 2.0 Posts are also added
great one.
Regards,
Milind.
Post a Comment