7
  • I need to know how to initialize array of arrays in C#..
  • I know that there exist multidimensional array, but I think I do not need that in my case! I tried this code.. but could not know how to initialize with initializer list..

    double[][] a=new double[2][];// ={{1,2},{3,4}};

Thank you

PS: If you wonder why I use it: I need data structure that when I call obj[0] it returns an array.. I know it is strange..

Thanks

5 Answers 5

5

Afaik, the most simple and keystroke effective way is this to initialize a jagged array is:

double[][] x = new []{new[]{1d, 2d}, new[]{3d, 4.3d}};

Edit:

Actually this works too:

double[][] x = {new[]{1d, 2d}, new[]{3d, 4.3d}};
Sign up to request clarification or add additional context in comments.

3 Comments

Wouldn't the first one be double[][] x = new[][] {?
So many unneccesary keystrokes... Just write it as double[][]x={new[]{1d,2},new[]{3,4.3}}; ;)
@Robert Harvey, actually kind of strange but no.
4

This should work:

double[][] a = new double[][] 
{ 
    new double[] {1.0d, 2.0d},
    new double[] {3.0d, 4.0d}
};

5 Comments

Seems like you are missing a "{" somewhere in the example.
you are missing a { after the [2][]
@ntziolis: It is on the following line.
You don't need the "2" specified.
You also don't need double just new[]
3

As you have an array of arrays, you have to create the array objects inside it also:

double[][] a = new double[][] {
  new double[] { 1, 2 },
  new double[] { 3, 4 }
};

Comments

2
double[][] a = new double[][] {
     new double[] {1.0, 1.0}, 
     new double[] {1.0, 1.0}
};

Comments

0

I don't know if I'm right about this, but I have been using socalled Structures in VB.net, and wondering how this concept is seen in C#. It is relevant to this question in this way:

' The declaration part
Public Structure driveInfo
    Public type As String
    Public size As Long
End Structure
Public Structure systemInfo
    Public cPU As String
    Public memory As Long
    Public diskDrives() As driveInfo
    Public purchaseDate As Date
End Structure

' this is the implementation part 
Dim allSystems(100) As systemInfo
ReDim allSystems(1).diskDrives(3)
allSystems(1).diskDrives(0).type = "Floppy"

See how elegant all this is, and far better to access than jagged arrays. How can all this be done in C# (structs maybe?)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.