Declaring an array within a structure

G

Guest

Hi All,

I need to declare an array in a structure. The following gives an error at
private char[] chararr = new char[5];
------------------------------------------------------
struct SimpleStruct
{
private int xval;
private char[] chararr = new char[5];

public SimpleStruct(int intval, char[] chararrval)
{
xval = intval;
for(int i = 0; i < 5; i++)
{
charr = chararrval;
}
}
}

Could anybody please post the correct declaration?

Thanks,
kd.
 
N

Nick Baldwin

You have to declare that property inside the constructor. Make it like so:

struct SimpleStruct
{
private int xval;
private char[] chararr;

public SimpleStruct(int intval, char[] chararrval)
{
chararr = new char[5];
xval = intval;

for(int i = 0; i < 5; i++)
{
charr = chararrval;
}
}
}
 
N

Nick Baldwin

And on second examination, it looks like you're trying to do this...

struct SimpleStruct
{
private int charsLength;
private char[] chars;

public SimpleStruct(char[] input)
{
charsLength = input.Length;
chars = new char[charsLength];
Array.Copy( input, chars, charsLength );
}
}
 
J

Jon Skeet [C# MVP]

Nick Baldwin said:
And on second examination, it looks like you're trying to do this...

struct SimpleStruct
{
private int charsLength;
private char[] chars;

public SimpleStruct(char[] input)
{
charsLength = input.Length;
chars = new char[charsLength];
Array.Copy( input, chars, charsLength );
}
}

Alternatively:

chars = (char[]) input.Clone();
 

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