I'm having trouble understanding this problem with creating a jagged array in C#. If you look at the code below, it compiles fine. But if I were to take the 2 lines that are assigning values to the array "places" and move them from within the method to within the class itself, the compiler starts complaining with a lot of strange errors.
At first I thought that its because of the usage of the 'new' keyword within a class (a class being just a definition whereas 'new' refers to an instance... you can't have an instance within a definition, can you?). But then I noticed the usage of the 'new' keyword in the initialization of "places" was OK even though it was initialized within the class. Please explain.
public class Place
{
string[][] places = new string[2][];
public void enumerate()
{
places[0] = new string[] { "Canada", "United States" };
places[1] = new string[] { "Calgary", "Edmonton", "Toronto" };
Console.WriteLine(places[0][1]);
}
}
EDIT: to be explicit, the error is produced when running
public class Place
{
string[][] places = new string[2][];
places[0] = new string[] { "Canada", "United States" };
places[1] = new string[] { "Calgary", "Edmonton", "Toronto" };
public void enumerate()
{
Console.WriteLine(places[0][1]);
}
}
errors received "array size cannot be specified in a variable declaration (try initializing with a "new" expression)" "invalid tokens =, {, in class" "namespace cannot directly contain members such as fields or methods"
United States.