Say I have code like this (or any kind of jagged structure):
var intListList = new List<List<int>> {
new() { 1, 2, 3 }
};
I'd like to use a collection expression here. Resharper (EAP) suggests this:
var intListList = new List<List<int>> {
[1, 2, 3]
};
But that doesn't compile.
This must be possible! What's the syntax?
Edit:
OK. So from the answers, instead of this, declaring the type in the expression:
// does not compile
var intListList = new List<List<int>> {
[1, 2, 3]
};
The type has to be declared explicitly, and there is no new()
:
// compiles!
List<List<int>> intListList = [[1, 2, 3]];
The syntax used for the jagged arrays from the What's new in C# 12:
// Create a jagged 2D array:
int[][] twoD = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
Seems to work for lists also:
List<List<int>> list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];