Reputation: 1
I have implemented one program in C++ which has union Datatype. Now I want to convert that program into c#.
I want to used same structure in c# but don't know what can be used in place of union datatype.
We are using Visual Studio 2013 and framework 4.5.2.0
Upvotes: 0
Views: 620
Reputation: 81493
There is no out-of-the-box Union
data type in C#
However, you can fake-it with a struct
and the FieldOffset
attribute I guess. You can do this because of the need for interoperability, also you sometimes see it used for a fast non-cast type conversion. Be warned though, it's considered extremely hacky.
[StructLayout(LayoutKind.Explicit)]
struct SomeType
{
[FieldOffset(0)] public int Myint;
[FieldOffset(0)] public byte Byte1;
[FieldOffset(1)] public byte Byte2;
[FieldOffset(2)] public byte Byte3;
[FieldOffset(3)] public byte Byte4;
}
Usage
var someType = new SomeType();
Console.WriteLine(someType.Myint);
someType.Byte1 = 2;
Console.WriteLine(someType.Myint);
someType.Byte2 = 4;
Console.WriteLine(someType.Myint);
Output
0
2
1026
Note : I would seriously consider using the more common language features in C#, rethink the problem and not use this hack.
Upvotes: 1
Reputation: 171
Unfortunately, C# provides no direct out of the "box solution" in comparison to C++' Union
data type. However, BitConverter
is an option if you're using the union to map the bytes of one of the types of the other.
For example:
int x = 15;
float y = BitConverter.ToInt32(BitConverter.GetBytes(x), 0);
& vice versa:
float y = 15f;
int x = BitConverter.ToInt32(BitConverter.GetBytes(y), 0);
Upvotes: 0