In the realm of programming, it’s a widespread practice to design types that provide access to collections of data. However, upon reviewing various codebases, a recurring pattern often emerges:
public List<Range> Ranges
{
get; set;
}
The problem at hand revolves around the mutability of a property, which opens the door to potentially replacing the entire collection—a practice discouraged by Microsoft. To align with best practices, it’s advisable to provide a method for replacing the collection instead of making the property writable.
To rectify this, you can either remove the setter altogether or opt for the init modifier, as exemplified below:
public List<Range> Ranges => _ranges;
Both binary and XML serialization support read-only properties containing collections.
This is related to violation CA2227 and this is how I have it setup in my .editorConfig: dotnet_diagnostic.CA2227.severity = warning
Summary
While reviewing the codebase I utilized for this article, I discovered 103 occurrences where the code needs to be fixed.
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
Make a one-time donation
Make a monthly donation
Make a yearly donation
Choose an amount
Or enter a custom amount
Your contribution is appreciated.
Your contribution is appreciated.
Your contribution is appreciated.
DonateDonate monthlyDonate yearlyIf 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.
Discover more from dotNetTips.com
Subscribe to get the latest posts sent to your email.
