sonar-dotnet icon indicating copy to clipboard operation
sonar-dotnet copied to clipboard

New Rule Idea: Do not nest collection initializer in object initializer

Open Tim-Pohlmann opened this issue 4 months ago • 1 comments

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.

Tim-Pohlmann avatar Oct 09 '24 08:10 Tim-Pohlmann