// You can initialize member fields/properties using a collection expression.
// This expression creates an IEnumerable<string> containing three elements ("Ben", "Jos", "Seb").
// The actual type of _names is '\u003C\u003Ez__ReadOnlyArray<T>' which is an internal type used for collection expressions that implements IEnumerable<T>.
static readonly IEnumerable<string> _names = ["Ben", "Jos", "Seb"];
// For interfaces that allow collection mutation, the collection expression usually creates a List<T> under-the-hood instead.
// (e.g. _mutableNames is of type List<string> here)
static readonly ICollection<string> _mutableNames = ["Ben", "Jos", "Seb"];
// We can return collection expressions directly from methods where the return type is compatible.
// Notice the expression evaluates to a type inferred by the return type of the method (List<int> in this case):
static List<int> ReturnList() => [1, 2, 3];
// And another example with int[]:
static int[] ReturnArray() => [1, 2, 3];
static void Test() {
// We can create various collection types easily:
List<int> oneTwoThreeList = [1, 2, 3];
IEnumerable<int> oneTwoThreeEnumerable = [1, 2, 3];
// Proving they all initialize as expected:
PrintEnumerableContents(oneTwoThreeList); // 1, 2, 3
PrintEnumerableContents(oneTwoThreeEnumerable); // 1, 2, 3
PrintEnumerableContents(ReturnList()); // 1, 2, 3
PrintEnumerableContents(ReturnArray()); // 1, 2, 3
Console.WriteLine(_names.First()); // Ben
_mutableNames.Add("Curie");
Console.WriteLine(_mutableNames.Last()); // Curie
// You can pass collection expressions directly to methods that expect a compatible type:
PrintEnumerableContents([1, 2, 3]); // 1, 2, 3
PrintEnumerableContents([]); // Nothing (empty collection)
// We can also use collection expressions with spans:
Span<int> oneTwoThreeSpan = [1, 2, 3];
ReadOnlySpan<int> oneTwoThreeReadOnlySpan = [1, 2, 3];
// Finally, there's also a new 'spread' operator that allows you to easily concatenate multiple collections together:
IEnumerable<int> triple = [..oneTwoThreeList, ..oneTwoThreeEnumerable, ..oneTwoThreeSpan];
PrintEnumerableContents(triple); // 1, 2, 3, 1, 2, 3, 1, 2, 3
}
static void PrintEnumerableContents(IEnumerable<int> enumerable) {
Console.WriteLine(String.Join(", ", enumerable.Select(i => i.ToString(CultureInfo.InvariantCulture))));
}
Code snippet taken from "Complete C# Quick Reference - C# 12".