Question

  • 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

Was it helpful?

Solution

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}};

OTHER TIPS

This should work:

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

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 }
};
double[][] a = new double[][] {
     new double[] {1.0, 1.0}, 
     new double[] {1.0, 1.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?)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top