Microsoft .NET Code Analysis: Simplify the New Expression for C#

I have been programming with Microsoft .NET since a year before its release. I must admit that I’ve never liked having to define a type twice when creating it, as in this example:

private Dictionary<int, Dictionary<int, byte[]>> _list = new Dictionary<int, Dictionary<int, byte[]>>();

I’ve always found it to be a time-consuming task to define a type twice like this. That’s why when var was introduced in .NET Framework 3.5 back in 2007, I began using it extensively. I’m aware that var has been a subject of controversy, with some people loving it like myself, while others hate it. However, it’s worth noting that var cannot be used to define a class-level field in the example above. From my personal experience, one of the reasons I preferred var was its convenience when performing search and replace operations to change a type.

Starting with .NET 5, a new way to create an object has been introduced, leveraging the simplified new expression syntax, as demonstrated below:

private Dictionary<int, Dictionary<int, byte[]>> _list = new();

I find this simplified expression particularly appealing, mainly because of its versatility – it can be used in various contexts! While I don’t have immediate plans to refactor existing code within methods to adopt this new expression, I have begun utilizing it consistently whenever I define a type in a field. Let me highlight some additional advantages of embracing this simplified expression:

  • Concise syntax: The simplified new expression allows for more concise object initialization syntax, reducing the need for explicit property or field assignments after object creation. This leads to cleaner and more readable code, especially when dealing with objects that have numerous properties.
  • Readability: By initializing properties or fields directly at the point of creation, the code becomes more self-contained and easier to understand. It eliminates the need for separate initialization methods or multiple constructor overloads, making the code more cohesive.
  • Immutable types: The simplified new expression is particularly useful for initializing properties of immutable types. With the init keyword, properties can be set only during object initialization and not modified afterward. This helps enforce immutability and reduces the risk of unintentional changes to object state.
  • Reduced boilerplate code: By eliminating the need for explicit property assignments, the simplified new expression reduces boilerplate code, resulting in fewer lines of code and improved maintainability. This can be especially beneficial when working with large objects or complex initialization logic.
  • Enhanced IDE support: Integrated development environments (IDEs) that support C# 9.0 or later versions provide improved IntelliSense and code completion for the simplified new expression. This enhances developer productivity by offering suggestions and automatically generating the required code for object initialization.

When I setup the IDE0090 code analysis in my .editorConfig it looks like this: dotnet_diagnostic.IDE0090.severity = suggestion

Summary

While reviewing the codebase I utilized for this article, I discovered 134 occurrences where the simplified new expression could be employed. Considering the magnitude of the refactoring required, it is essential to streamline the process. Tools like CodeRush from DevExpress offer valuable extensions that simplify the refactoring task to a single mouse click, making the process efficient and convenient.

For further guidance and insights, I highly recommend obtaining a copy of my book, “Rock Your Code: Coding Standards for Microsoft .NET” available on Amazon.com. Additionally, to explore more performance tips for .NET, I encourage you to acquire the 3rd edition of “Rock Your Code: Code & App Performance for Microsoft .NET” also available on Amazon.com.

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. I update this file quarterly, so remember to keep yours up to date as well. I hope you will check out my OSS project Spargine by using this link: https://bit.ly/Spargine.

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

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

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 preproduced in any way without express permission from David McCarter.

One thought on “Microsoft .NET Code Analysis: Simplify the New Expression for C#

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.