Is there a kind of union structure in C Sharp?

I want to use "union" structure in C#,but can't find it!

Can u help me

Thanks in advance!




Answer this question

Is there a kind of union structure in C Sharp?

  • TalhaAziz

    variable A and variable B share the same memory space!

  • vTyphoon

    Are you able to show an example of what you mean

    do you happen to mean a structure layout

    do you mean something like...

    [StructLayout(LayoutKind.Explicit)
    class MyUnion

    [FieldOffset(0)] byte byte1
    [FieldOffset(1)] byte byte2
    [FieldOffset(2)] byte byte3
    [FieldOffset(3)] byte byte4
    [FieldOffset(0)] int myInt



  • Ramakrishna_Rao

    Thank you very much!

    That's what I want !



  • Quimbo

    And about how to simulate C++ union in C# is described underneath:

    In C++, Union expression is:

    union UValue
    {
        
    char _cval;
        
    int _ival;
        
    double _dval;
    }
    ;

    And in C#, to apoint where the members'd be located in the memory space, we need to use StructLayoutAttribute, LayoutKind enum and FieldOffsetAttribute, which are all in the namespace System.Runtime.InteropServices.

    Then, use struct to simulate the union above:

    [StructLayout(LayoutKind.Explicit, Size=8)]
    struct UValue
    {
        [FieldOffset(
    0)]
        
    public char _cval;

        [FieldOffset(
    0)]
        
    public int _ival;

        [FieldOffset(
    0)]
        
    public double _dval;
    }

    As we know, every member of union's address starts with the same position of memory. By adding [FieldOffset(0)] to each member of UValue, we can make they share the same memory space. Of course, we must tell .NET that the distribution of these members is up to ourselves in advance by passing LayoutKind.Explicit to constructor of StructLayoutAttribute (then to UValue). In addition, explicitly set the size of UValue 8 bytes is optional. (in this case double which cost most needs 8 bytes)

     



  • Ralph Morton

    Hi, soldier

    A union is a user-defined data or class type that, at any given time, contains only one object from its list of members (although that object can be an array or a class type). (In C or C++)

    A C++ union is a limited form of the class type. It can contain access specifiers (public, protected, private), member data, and member functions, including constructors and destructors. It cannot contain virtual functions or static data members. It cannot be used as a base class, nor can it have base classes.

    And in C#, union is not supported, but you can also simulate C++ union in C#.

    Thank you



  • Is there a kind of union structure in C Sharp?