-2

Is there a less verbose way to init this jagged array ?

    var r = new int[a.Length][];
    for (int i=0; i<a.Length; i++)
    {
        r[i] = new int[2];
    }

I don't want a multidimensional array int[,] because I may later need to assign to some elements other than int[2]

BaltoStar
  • 8,165
  • 17
  • 59
  • 91

2 Answers2

1

The answer is no, you cant implicitly default a jagged array on initialisation.

Jagged arrays are actually just an array of something (int this case another array) and as such each element has to be initialised by its self.

May i suggest using

  • A Multidimensional Array instead, this will in turn be defaulted on initialisation.

  • Failing that you can write a generic helper to default and initialise

  • Or an Extension Method

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
  • 1
    for my case a multidimensional array could be quite sparse, for example i might have `a[0]=int[2] ....... a[1000]=int[100]` which would imply `int[1000,100]` which i assume allocates far more memory than `int[1000][]` – BaltoStar Oct 03 '18 at 01:31
1

The Linq equivalent is only slightly less verbose:

int[][] r = Enumerable.Range(1,a.Length)
                      .Select(i => new int[2])
                      .ToArray();
D Stanley
  • 149,601
  • 11
  • 178
  • 240