SonarSource / sonar-dotnet

Code analyzer for C# and VB.NET projects
https://redirect.sonarsource.com/plugins/csharp.html
GNU Lesser General Public License v3.0
797 stars 229 forks source link

New Rule Idea: Do not use collection initializers with `ImmutableArray` #9681

Open Tim-Pohlmann opened 1 month ago

Tim-Pohlmann commented 1 month ago

Using a collection initializer with the ImmutableArray type, causes a NullReferenceException.

_ = new ImmutableArray<string> { "init" }; // NRE

SharpLab

jilles-sg commented 1 month ago

This NRE is a special case of the fact that the parameterless constructor of ImmutableArray<T> results in an object that throws on most access. Perhaps the new rule can trigger on uses of that constructor instead. If a "null" value of ImmutableArray<T> is needed, I'd say the developer should be explicit and write default.