-1

I have a list of integer arrays:

List<int[]> MyList = new List<int[]>();

When trying to add an array to this list like this:

MyList.Add({ i, j });

The program won't compile, however this it has no issue with

int[] k = { i, j };
MyList.Add(k);

Why is the first method not valid and is there a better way than the second to carry out this task?

Andrew Neate
  • 109
  • 1
  • 9
  • 4
    Possible duplicate of [Add Object Collection to another Object Collection without iterating](https://stackoverflow.com/questions/9492404/add-object-collection-to-another-object-collection-without-iterating) – Jota.Toledo Dec 13 '17 at 15:56

3 Answers3

3

{ i, j } is short syntax for creating a new array and currently it only works at declarations. you can not use the same syntax for creating array anywhere else.

you can write

MyList.Add(new[]{ i, j });
M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118
2

You can use this.

  MyList.Add(new int []{ i, j });
Serkan Arslan
  • 13,158
  • 4
  • 29
  • 44
0

Use MyList.Add(new int[] { i, j });

Markiian Benovskyi
  • 2,137
  • 22
  • 29