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 nest collection initializer in object initializer #9680

Open Tim-Pohlmann opened 1 month ago

Tim-Pohlmann commented 1 month ago

Nesting a collection initializer inside an object initializer can have unexpected side effects or lead to crashes:

var x = new Evil { Arguments = { "two", "three" } };
Console.WriteLine(x.Arguments.Count);    // 3!

class Evil  
{
    public List<string> Arguments { get; } = [ "one" ];
}

SharpLab

var x = new Evil { Arguments = { "two", "three" } };    // NRE!

class Evil  
{
    public List<string> Arguments { get; }
}

SharpLab

Even if the argument is initialized with an empty collection (and the constructor does not do any shenanigans either), this kind of code relies heavily on implementation details and is unintuitive to understand.

pavel-mikula-sonarsource commented 1 month ago

Same likely applies to dictionary initializer(s) too. Basically any sugar that is translated to .Add calls