Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C-like Union in C#

How may I achieve a union, functioning like in C, in C#?
**My concrete scenario is as follows: **

I want to have a union with two Fields, one Int128 and one Decimal.
As these two types require the same amount of memory (8 bytes) I want to reinterpret them as the other type.
Essentially, I want to know what this C Union would look like in C# (I am using the corresponding C# types):

union Sample{
    Int128 Value1;
    Decimal Value2;
};

I would be relieved if anyone had any idea!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You may achieve a union, like in C, in C# by adding the FieldOffset(0) attribute to the fields for which you want union-like behaviour. Instead of a dedicated union type it is required to use C#’s struct. Your entire struct would need to have the attribute StructLayout(LayoutKind.Explicit).
What this means, is that you want to expicitly control the layout of your struct by yourself and by attributing the fields with FieldOffset(0), you essentially put both fields in the same place in memory, therefore depending on which one you will access, you will have the memory reinterpreted as the type of the field.

Your final code may look somewhat like this:

[StructLayout(LayoutKind.Explicit)]
struct Sample
{
    [FieldOffset(0)]
    public decimal ValueDecimal;
    
    [FieldOffset(0)]
    public Int128 ValueInteger;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading