SSW Foursquare

C# Code - Do you use collection expressions to keep your code clean?

Last updated by Daniel Mackay [SSW] 5 months ago.See history

Do you know collection expressions can make your code cleaner? They can be used to create arrays, lists, and other collections in a single line of code.

var numbers1 = new List<int> {1, 2, 3, 4, 5};

Figure: Bad example - Verbose way of constructing a list

var numbers2 = new[] { 1, 2, 3, 4, 5 };

Figure: OK example - using implicit arrays

List<int> numbers3 = [1, 2, 3, 4, 5];

Figure: Good example - using collection expressions

Another advantage of collection expressions is that they can be passed into methods accepting different types of list collections. The compiler is smart enough to determine the correct underlying type.

Foo([1,2,3]);
Foo2([1,2,3]);
Foo3([1,2,3]);

void Foo(IEnumerable<int> numbers)
{
    // Do work
}

void Foo2(List<int> numbers)
{
    // Do work
}

void Foo3(int[] numbers)
{
    // Do work
}

Figure: Versatile use of collection expressions in methods with varying collection types

For more information on collection expressions see here: learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/collection-expressions

We open source. Powered by GitHub