Defining a union

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
 
G

Göran Andersson

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?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top