A very nice innovation from C# 12.0 is the simplified syntax for initializing sets. Microsoft originally called this language feature Collection Literals, but now called Collection Expressions.
Advertisement
Dr. Holger Schwichtenberg is Chief Technology Expert at MAXIMAGO, which offers innovation and experience-driven software development, including in highly critical safety-related areas. He is also head of the expert network www.IT-Visions.de, which supports numerous medium-sized and large companies with advice and training in the development and operation of software with 43 renowned experts.
With this new syntax you can greatly unify the previously very heterogeneous initialization forms of object sets in the style of JavaScript, i.e. with the values āāin square brackets, separated by commas:
Previous initialization Now also possible int[] aĀ =Ā newĀ int[3] {Ā 1,Ā 2,Ā 3Ā };
int[] aĀ = [1,2,3];Ā Ā Ā Ā Ā
Span
Span
ImmutableArray
ImmutableArray
List
List
IEnumerable
IEnumerable
The syntax with square brackets is possible not only during initial initialization, but also during later assignments:
List
sites1 = [āwww.dotnetframework.deā, āwww.dotnet8.deā,
ādotnet-lexikon.deā, āwww.dotnet-doktor.deā];
sites3 = []; // empty list
With the spread operator .. you can integrate sets into other sets as part of the initialization. The spread operator ensures that a flat list is not nested:
// Create an array from the elements of the arrays using spread operator string[] allSitesAsArray =
[.. sites1, .. sites2, āwww.dotnettraining.deā, .. sites3]; // Create a list from the elements of the arrays using Spread Operator List
[.. sites1, .. sites2, āwww.dotnettraining.deā, .. sites3]; // Expand the list again allSitesAsList = [.. allSitesAsList, āpowershell-schulungen.deā]; // List: 7 sites are now in the list foreach (var site in allSitesAsList) { Console.WriteLine(site); }
A lot is created with these eight sites, because in addition to the seven sites contained in the sites1, sites2, and sites3 variables, another site has been added.
Output of the previous listing
(Bild:Ā Screenshot / Holger Schwichtenberg)
Collection expressions are not currently possible for dictionary objects (as of C# 12.0). With these you can (as before C# 12.0) either use the initialization using nested curly brackets or use the name-value assignment within the curly brackets via [Name] = do value:
// Initialization with Add() SortedDictionary
{
[10] = āwww.dotnet-doktor.deā,
[21] = āwww.dotnetframework.deā,
[42] = āwww.dotnet8.deā
};
(rme)
To home page