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

Updated by Brady Stroud [SSW] 1 year ago. See history

123
No component provided for introEmbed
var numbers1 = new List<int> {1, 2, 3, 4, 5};

❌ Figure: Figure: Bad example - Verbose way of constructing a list

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

😐 Figure: Figure: OK example - using implicit arrays

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

✅ Figure: 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

Acknowledgements

Daniel Mackay
Related rules

Need help?

SSW Consulting has over 30 years of experience developing awesome software solutions.

We open source.Loving SSW Rules? Star us on GitHub. Star