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