How can I initialize a IList<IList<string>>?
Solution 1
You'd need:
IList<IList<string>> matrix = new List<IList<string>>();
but then you can happen to always add a List<string>
for each element.
The reason this won't work:
// Invalid
IList<IList<string>> matrix = new List<List<string>>();
is that it would then be reasonable to write:
// string[] implements IList<string>
matrix.Add(new string[10]);
... but that would violate the fact that the list is really a List<List<string>>
- it's got to contain List<string>
values, not just any IList<string>
... whereas my declaration at the top just creates a List<IList<string>>
, so you could add a string array to it without breaking type safety.
Of course, you could change to use the concrete type in your declaration instead:
IList<List<string>> matrix = new List<List<string>>();
or even:
List<List<string>> matrix = new List<List<string>>();
Solution 2
try this
IList<IList<string>> matrix = new List<IList<string>>();
Solution 3
This will work - you can't initialize a generic type parameter the way you tried:
IList<IList<string>> matrix = new List<IList<string>>();
Though, the inner IList<string>
will be null
. To initialize it you can do the following:
matrix.Add(new List<string>());
Solution 4
if matrix is of constant size arrays are a better fit
string[][] matrix = new string[size];
matrix[0] = new string[5];
matrix[1] = new string[8];
matrix[2] = new string[7];
and if it is rectangular
string[,] matrix = new string[sizex,sizey];
markzzz
Updated on June 27, 2022Comments
-
markzzz almost 2 years
Tried with :
IList<IList<string>> matrix = new List<new List<string>()>();
but I can't. How can I do it? I need a matrix of strings...