views:

151

answers:

5
  • 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

+4  A: 

This should work:

double[][] a = new double[][] 
{ 
    new double[] {1.0d, 2.0d},
    new double[] {3.0d, 4.0d}
};
Robert Harvey
Seems like you are missing a "{" somewhere in the example.
cyberzed
you are missing a **{** after the [2][]
ntziolis
@ntziolis: It is on the following line.
Robert Harvey
You don't need the "2" specified.
Taylor Leese
You also don't need `double` just `new[]`
Pop Catalin
+3  A: 

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 }
};
Guffa
+2  A: 
double[][] a = new double[][] {
     new double[] {1.0, 1.0}, 
     new double[] {1.0, 1.0}
};
Taylor Leese
+4  A: 

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}};
Pop Catalin
Wouldn't the first one be `double[][] x = new[][] {`?
Robert Harvey
So many unneccesary keystrokes... Just write it as `double[][]x={new[]{1d,2},new[]{3,4.3}};` ;)
Guffa
@Robert Harvey, actually kind of strange but no.
Pop Catalin
A: 

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?)

netfed