Creating an array within a structure
How can I create a string or char array of a fixed length within a structure. Every thing I try generates an array size error.
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
AlanPosted Oct 22, 2007, 12:30 PM
Instance fields within a struct cannot be initialized 'in situ'. They're normally initialized in the constructor, so you could do something like this to create a char[] of a given size:
using System;
class Test
{
static void Main()
{
char[] myArray = new char[]{'H', 'e', 'l', 'l', 'o'};
MyStruct ms = new MyStruct(myArray);
Console.WriteLine(new string(ms.MyArray));
Console.ReadLine();
}
struct MyStruct
{
private char[] myArray;
public char[] MyArray
{
get {return myArray; }
}
public MyStruct(char[] ca)
{
myArray = ca;
}
}
}
Notice though that you can't fix the size of the char[] field in advance. myArray could be assigned an array of any size.
Similarly, with string fields you can't fix the length in advance. They can be assigned a string of any length.
The only exception to this is if you're using C# 2.0 (or later) in 'unsafe' mode (for interop say). You can then use a fixed size char buffer as explained here:
http://msdn2.microsoft.com/en-us/library/zycewsya(VS.80).aspx