General Performance: Null Coalescing Assignment

C# 8 introduced the null-coalescing assignment operator (??=), and in modern C# you can combine it with collection expressions:

List<Person>? list = null;

list ??= [];

Here, [] is a collection expression that creates a new List<Person>() because the compiler infers the target type from list.

Before C# 8, the code for this operation appeared:

if (list == null)
{
    list = new List<Person>();
}

Performance Breakdown

Benchmarks show that the null-coalescing operator (??=) is slightly more performant and dramatically more readable in modern C#.

Favor the null-coalescing operator for its clarity, conciseness, and measurable (though modest) performance advantage.

Always benchmark any changes using tools like BenchmarkDotNet to ensure your optimizations result in measurable improvements in your actual codebase.

To analyze your code using the same settings I used in these articles, I encourage you to incorporate my EditorConfig file. It can be found at the following link: https://bit.ly/dotNetDaveEditorConfig.

Please feel free to leave a comment below. I would appreciate hearing your thoughts and feedback.

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

If you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave

© The information in this article is copywritten and cannot be reproduced in any way without express permission from David McCarter.


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

Leave a Reply