.NET 11 Preview - Collection Expression Arguments
[C#, .NET, .NET 11 Preview]
One of the more brilliant innovations in C# 12 was collection expressions.
Typically, initializing a collection required code specific to that expression. Take the following examples:
// Initialize a list
List<string> namesList = new List<string>() { "Brenda", "Latisha", "Linda", "Felicia" };
// Initialize an array
string[] nameArray = new string[] { "Brenda", "Latisha", "Linda", "Felicia" };
// Initialize a HashSet
HashSet<string> nameHashSet = new HashSet<string> { "Brenda", "Latisha", "Linda", "Felicia" };
You can simplify the code for the List and the HashSet as follows:
// Initialize a list
List<string> namesList = new() { "Brenda", "Latisha", "Linda", "Felicia" };
// Initialize a HashSet
HashSet<string> nameHashSet = new() { "Brenda", "Latisha", "Linda", "Felicia" };
Unfortunately, for a string array, it cannot get any simpler.
This problem is solved with collection expressions.
This means there is a universal syntax for initializing collections.
// Initialize a list
List<string> namesList = ["Brenda", "Latisha", "Linda", "Felicia"];
// Initialize an array
string[] nameArray = ["Brenda", "Latisha", "Linda", "Felicia"];
// Initialize a HashSet
HashSet<string> nameHashSet = ["Brenda", "Latisha", "Linda", "Felicia"];
You can see here that it does not matter the type of collection; initialization is the same.
The problem with this syntax is that there are times you need to initialize some properties on the collection.
For example, with a List, you can set its size in advance to prevent the runtime from having to recreate the object as it grows.
var names = new List<string>(40);
Here we want our List to have a preallocated size of 40.
It has not been possible to do this with collection expressions.
This is now possible in .NET 11.
Your code would look like this:
List<string> namesList = [with(capacity: 4), "Brenda", "Latisha", "Linda", "Felicia"];
If you are initializing the collection from another collection, your code would look like this:
string[] otherCollection = ["Brenda", "Latisha", "Linda", "Felicia"];
List<string> namesList = [with(capacity: 4), .. otherCollection];
Important: This is a preview language feature, and to get it to compile, you must include the following in your .csproj file.
<LangVersion>preview</LangVersion>
It should now look like this:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>preview</LangVersion>
</PropertyGroup>
</Project>
TLDR
You can pass parameters to collections during initialization using the [with] keyword.
The code is in my GitHub.
Happy hacking!