Initializing collections such as arrays, lists and spans can be verbose. This feature introduces a shorthand syntax for creating collections that uses square brackets [] instead of calling constructors.
Code
csharp
char[] a = [ 'z', 'x', '4', '8' ];
List<string> l = ["one", "two", "three"];
Span<int> s = [1, 2, 3, 4, 5];
Span<char> c = [..myArray, 'k'];csharp
char[] a = new[] { 'z', 'x', '4', '8' };
List<string> l = new() { "one", "two", "three" };
Span<int> s = new[] { 1, 2, 3, 4, 5 };
Span<char> c = new(myArray.Append('k').ToArray());Notes
- The spread element
..copies every item from any enumerable collection into the new one []creates an empty collection of the target type- Collection expressions have no natural type, so
var x = [1, 2];does not compile - Collection expression arguments C# 15.0 let you pass constructor arguments such as a capacity or comparer