Open Tim-Pohlmann opened 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; } }
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.
Same likely applies to dictionary initializer(s) too. Basically any sugar that is translated to .Add calls
.Add
Nesting a collection initializer inside an object initializer can have unexpected side effects or lead to crashes:
SharpLab
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.