Skip to content

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

Open
@Tim-Pohlmann

Description

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.

Metadata

Assignees

No one assigned

    Labels

    Area: C#C# rules related issues.Type: Rule IdeaIdea for a rule that has NOT been specified.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions