Re: Defining a union
- From: Göran Andersson <guffa@xxxxxxxxx>
- Date: Sat, 03 Jan 2009 04:08:05 +0100
lchaplin13@xxxxxxxxx wrote:
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?
--
Göran Andersson
_____
http://www.guffa.com
.
- References:
- Defining a union
- From: lchaplin13@xxxxxxxxx
- Defining a union
- Prev by Date: Defining a union
- Next by Date: Re: How to pass a vc++ BSTR value to C#.Net
- Previous by thread: Defining a union
- Next by thread: I need to find whether all the check boxes are checked or not in a page
- Index(es):
Relevant Pages
|