Skip to content

Collection expressions C# 12.0code reductionreadability

A short syntax for initializing collections.

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

C#
char[] a = [ 'z', 'x', '4', '8' ];

List<string> l = ["one", "two", "three"];

Span<int> s = [1, 2, 3, 4, 5];

Span<char> c = new(myArray.Append('k').ToArray());
C#
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 = [..myArray, 'k'];

Notes

  • You can use the spread operator .. to append an array to another array
  • You can also use the range operator .. to create a slice of an another array

More information