Defining a union

  • Thread starter Thread starter lchaplin13
  • Start date Start date
L

lchaplin13

Hi all,
I would like to convert the following C code into C#, any help will be
greatly appreciated:

union real{
int n;
float x;
} answer1;

union realdouble{
int n[2];
double x;
} answer2;

I've tried already
[StructLayout(LayoutKind.Explicit)]
public struct Real
{
[FieldOffset(0)]public int n;
[FieldOffset(0)]public float x;
}
but I get the error "Use of possibly unassigned field 'n' (CS0170)"
Real answer1;
answer1.x = inputValue;
Console.Write("Real Value = {0} \n", answer1.n);
For the second union I don't have a clue...

Thanks,
Lee
 
Hi all,
I would like to convert the following C code into C#, any help will be
greatly appreciated:

union real{
int n;
float x;
} answer1;

union realdouble{
int n[2];
double x;
} answer2;

I've tried already
[StructLayout(LayoutKind.Explicit)]
public struct Real
{
[FieldOffset(0)]public int n;
[FieldOffset(0)]public float x;
}
but I get the error "Use of possibly unassigned field 'n' (CS0170)"
Real answer1;
answer1.x = inputValue;
Console.Write("Real Value = {0} \n", answer1.n);
For the second union I don't have a clue...

Thanks,
Lee

The reason that you get that error is that the field is unassigned. The
compiler doesn't take in account that the field occupies (partly or
completely) the same memory area as another field.

To make the second struct work you would also have to use attributes to
make an inline array. I don't remembter exactly how that is done.

How about scrapping the structs altogether and use the GetBytes,
ToSingle and ToDouble methods of the BitConverter class?
 
Back
Top