Stoodent
Stoodent

Reputation: 155

Why is this 2D array initialization illegal?

Can someone explain why the below initialization of "board" not working? Here's my code:

public partial class frmSudoku : Form
{
   Label[,] board;    

   public frmSudoku()
   {
      InitializeComponent();
      board = {{lblS00, lblS01, lblS02, lblS03, lblS04, lblS05, lblS06, lblS07, lblS08},
                 {lblS10, lblS11, lblS12, lblS13, lblS14, lblS15,lblS16,lblS17, lblS18},
                 {lblS20, lblS21, lblS22, lblS22, lblS24, lblS25, lblS26, lblS27, lblS28},
                 {lblS30, lblS31, lblS32, lblS33, lblS34, lblS35, lblS36, lblS37, lblS38},
                 {lblS40, lblS41, lblS42, lblS43, lblS44, lblS45, lblS46, lblS47, lblS48},
                 {lblS50, lblS51, lblS52, lblS53, lblS54, lblS55, lblS56, lblS57, lblS58},
                 {lblS60, lblS61, lblS62, lblS63, lblS64, lblS65, lblS66, lblS67, lblS68},
                 {lblS70, lblS71, lblS72, lblS73, lblS74, lblS75, lblS76, lblS77, lblS78},
                 {lblS80, lblS81, lblS82, lblS83, lblS84, lblS85, lblS86, lblS87, lblS88}};
 }

I'm on VS2019 and there are those red underlines under each comma - their error messages are just "; expected" (which is clearly not right; I tried replacing it with a semicolon just to see and the red underline just shifted under the labels with an error message of "Only assignment, call, decrement ... can be used as a statement"). I really don't know why this is illegal - I tried declaring a 2D int array under public partial class and initializing it similarly in frmSudoku() and it worked fine. What makes a label array different?

EDIT: The 2D int array did not work fine, it just took a while for the red underlines to show up (oops)

Upvotes: 1

Views: 294

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500495

This isn't unique to 2D arrays. Using the terminology from the ECMA C# Standard, an array-initializer is only valid within an array-creation-expression, a field declaration, or a local variable declaration.

So for example, this is valid:

// array-initializer as part of a local variable declaration
string[] strings = { "x", "y" };

But this isn't:

string[] strings;
// This is just an assignment expression, not part of a variable declaration
strings = { "x", "y" };

You can use an *array-creation-expression( though:

string[] strings;
strings = new string[] { "x", "y" };

The equivalent applies to your 2-D example:

board = new Label[,] {{ ... }};

Upvotes: 8

Related Questions