Shay Lugassy Shay Lugassy -4 years ago 197
C# Question

C# - float[][] declaration

I'm trying to declare this kind of variable:

float[][]


Things that didn't work for me (wouldn't compile) -

float[][] inputs = new float[10][5];
float[][] inputs = new float[10,5];


When trying to declare the array like this -

int a = 3;
int b = 2;
float[][] inputs = new float[][]
{
new float[a],
new float[b]
};


I get a multidimensional array with two float arrays instead of an array that has 3 arrays and every array size is 2.

Answer Source

Well, there are two different types:

  • Array of array (jagged array):

    float[][] sample = new float[][] {
      new float[] {1, 2, 3},
      new float[] {4, 5}, // notice that lines are not necessary of the same length
    };
    
  • 2d array:

    float[,] sample2 = new float[,] {
      {1, 2, 3},
      {4, 5, 6},
    };
    

Edit: your code amended:

  // jagged array (10 arrays each of which has 5 items)
  float[][] inputs = new float[10][] {
    new float[5],
    new float[5],
    new float[5],
    new float[5],
    new float[5],
    new float[5],
    new float[5],
    new float[5],
    new float[5],
    new float[5],
  };

You can shorten the declaration with a help of Linq:

  float[][] inputs = Enumerable
    .Range(0, 10)               // 10 items
    .Select(i => new float[5])  // each of which is 5 items array of float
    .ToArray();                 // materialized as array

Or in case of 2d array

  // 2d array 10x5
  float[,] inputs = new float[10,5];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download