[C#] Array in struct

Started by
3 comments, last by dalep 17 years, 2 months ago
struct Fruits { char Apple; bool Cherry; int Orange[100]; // Error here long Melon; } The struct above well works in C++, but gives error in C#. How can I write C# version of this code? Error given :
Error 1 Syntax error, bad array declarator. To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type. Error 2 Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
Advertisement
int[] oranges;

somefruit.oranges = new int[100];
I asked this question to some other forums about three or four weeks ago, no answer yet.
Again I asked it to one of my friend who claims to have a certificate in C#, he said that I must use array lists and it is a very difficult thing to implement.

But you answered just a few minutes after I asked this question, and it works alright. Thank you very much!
This is what I like about GameDev.

By the way my
and blocks are not working, is that a temporary problem? Also advanced reply mode is disabled. How can I reactivate it?
It should be noted that that allocates an array on the managed heap. There is no method to allocate managed arrays on the stack.

Use lowercase letters,
and

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

If you need an array in a struct for interop (like passing out to a DLL or something) you can do it like this:
public unsafe struct StructWithAnArray{    public fixed int ArrayField[100];}

You could only use this in an unsafe context and the type of the array can only be a native numeric value type (int, double, float, etc). ArrayField isn't an actual Array so you can't pass it to anything expecting a parameter of type System.Array and it doesn't have any properties like Length. Within your C# code, ArrayField is of type int* but sizeof(StructWithArray) will return 400.

I've never had occasion to actually do this so I have no idea what the pitfalls might be.

This topic is closed to new replies.

Advertisement