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
        internal struct Union
            internal char theChar;
            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.ReadKey(); //keep console on screen until keypress
7 Years
Discussion Span
Last Post by ddanbe

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:$

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.