Tuesday, October 24, 2023

C# 12.0: Collection Expressions and Spread Operator

We are less than a month away from .NET 8 official release (.NET Conf 2023: November 14-16, 2023) and in this post, let's have a look at a nice feature in   C# 12.0 which is getting shipped along with .NET 8.

You can try this feature with the latest preview of Visual Studio 2022 (as of today it's 17.8.0 Preview 4.0). And remember to set LangVersion as preview.

We can now express a collection as follows.
string[] workingDays = [ "Monday""Tuesday""Wednesday""Thursday""Friday" ];
string[] weekEnds = [ "Saturday""Sunday" ];
A collection expression contains a sequence of elements between [ and ] brackets.

You use a spread element .. to spread out collection values in a collection expression.
IEnumerable<stringdays = [.. workingDays, .. weekEnds];

Console.WriteLine(days.Count());
// 7

foreach (string day in days)
{
    Console.WriteLine(day);
}
// Monday
// Tuesday
// Wednesday
// Thursday
// Friday
// Saturday
// Sunday
You can even pass collection expressions into a method as follows.
IEnumerable<EmployeeitEmployees = [new Employee("John""IT"), new Employee("Jane""IT")];
IEnumerable<EmployeehrEmployees = [new Employee("Joe""HR")];

Console.WriteLine(Count([.. itEmployees, .. hrEmployees]));
// 3

int Count(IEnumerable<Employeevalues) => values.Count();

record Employee(string Namestring Department);

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment