Constant Struct in C#

  • Thread starter Thread starter QQ
  • Start date Start date
Q

QQ

How do I declare a constant array of struct in C# ?

struct TEST
{
int x;
int y;
};

TEST[] test = { {1, 2}. {2. 3} };

The above doesn't compile. Any idea ?
 
Hi QQ,

Well, for one, x and y is private to the struct and won't be accessible. Then you use a strange mix of . and , And lastly, you can only initialize arrays like this for variables or fields. So, as DarekB said, you need to set each value manually.

struct TEST
{
public int x;
public int y;
}

TEST[] test = new TEST[2];

test[0].x = 1;
test[0].y = 2;
test[1].x = 2;
test[1].y = 3;


Happy coding!
Morten Wennevik [C# MVP]
 
I think it would be best to do it like this:
Implement a constructor fo the struct.
and use them.


// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// define the struct like this
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
struct tTEST
{
public tTEST(int ix, int iy)
{ x = ix; y = iy;
}
int x;
int y;
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// later
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
tTEST[] test = { new tTEST(1, 2), new tTEST(2, 3) };
 

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

Back
Top