Jagged arrays

  • Thread starter Thread starter Femi
  • Start date Start date
F

Femi

Hello,

Can anyone help? I get the error message below:

Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)

Code snippet:

Class Test{

string [][] MyString = new string [3][];
MyString[0] = new string[5];
}

Thanks
 
Femi said:
Can anyone help? I get the error message below:

Array size cannot be specified in a variable declaration (try
initializing with a 'new' expression)

Code snippet:

Class Test{

string [][] MyString = new string [3][];
MyString[0] = new string[5];
}

Those two lines world work inside a method but not outside.

Arne
 
Further to Arne's reply, you could also use array-initializer syntax
(below), but it seems unlikely that you would generally know these
numbers at compile-time; as such, the constructor is a good place to
consider.

string[][] MyString = { new string[5], new string[2], new
string[10] };

(note: only verified on C#3; my 2.0 machine is unavailable)

Marc
 
Why isn't this documented
I'm assuming you mean "that you can't use regular code outside of a
method" - this is documented in many, many places. In particular the
language spec.

Re the sample - it doesn't say that "jaggedArray" is a field. The code
as presented would be perfectly valid as contents of a method, with
"jaggedArray" as a local variable.

Marc
 
Femi said:
Thank you all.

What gets me is that I followed the example on MSDN
http://msdn2.microsoft.com/en-us/library/2s05feca(VS.80).aspx


Why isn't this documented

It is.
In the language specification. Section 17 defines what a class can contain.

Informally, a class contains a class-body, which contains 0...n
class-member-declarations, which can be any of:

constant-declaration
field-declaration
method-declaration
property-declaration
event-declaration
indexer-declaration
operator-declaration
constructor-declaration
finalizer-declaration
static-constructor-declaration
type-declaration

string [][] MyString = new string [3][];

This is a field-declaration. It happens to contain a variable-initializer.

MyString[0] = new string[5];

This is just an assignment, which is not valid here.

Alun Harford
 
Back
Top