Hi all,
I'm trying to implement a C-style union in C#.
Found things on the web, but I have a problem. Depending how I initialize the fields in the union I get different results.
Can anyone tell me what am I doing wrong here?
Here is my code:
using System;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
class Program
{
[StructLayout(LayoutKind.Explicit)]
internal struct Union
{
[FieldOffset(0)]
internal char theChar;
[FieldOffset(0)]
internal bool theBool;
}
static void Main(string[] args)
{
Union union = new Union();
union.theChar = 'A'; //--> when I do this, char gets messed up
union.theBool = true;
//union.theChar = 'A'; --> when I do this, output OK
Console.WriteLine(union.theChar);
Console.WriteLine(union.theBool);
Console.ReadKey(); //keep console on screen until keypress
}
}
}