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
        }
    }
}

Trick question? In the active code lines, you are overwriting the first byte of your char "theChar", which is two bytes (Unicode) in length, when you assign to your bool "theBool", which is one byte in length; because you have aligned both fields on the first byte ([FieldOffset(0)]) in your structure.

And they said you couldn't do unions in C#. Just don't expect any language support for bitwise manipulation.:icon_smile:

Also, anything other than 0x00000000 in the boolean address would probably be translated true, though I haven't tested that.

Thanks for the reply, and believe me this is NO trick question!
I thought that a union was meant for that, to be two or more things at once. But you are right, after what you said I did some more tests (perhaps I should have done that in the first place) it does not work that way :'(
You gave me insights, thanks.

Epilog : I must admit, I'm in an off day today and I posted this too early:$

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.