Why is an Add method required for { } initialization?

前端 未结 9 2158
渐次进展
渐次进展 2021-02-10 18:54

To use initialization syntax like this:

var contacts = new ContactList
{
    { \"Dan\", \"dan.tao@email.com\" },
    { \"Eric\", \"ceo@google.com\" }
};
<         


        
9条回答
  •  眼角桃花
    2021-02-10 19:07

    I'm sure I haven't put as much thought into this matter as the C# design team; it just seems that there could have been different rules for this syntax that would have meshed better with its typical usage scenarios.

    Your analysis is very good; the key problem is the last three words in the statement above. What are the actual typical usage scenarios?

    The by-design goal motivated by typical usage scenarios for collection initializers was to make initialization of existing collection types possible in an expression syntax so that collection initializers could be embedded in query comprehensions or converted to expression trees.

    Every other scenario was lower priority; the feature exists at all because it helps make LINQ work.

    The C# 3 compiler team was the "long pole" for that release of Visual Studio / .NET - we had the most days of work on the schedule of any team, which meant that every day we delayed, the product would be delayed. We wanted to ship a quality product on time for all of you guys, and the perfect is the enemy of the good. Yes, this feature is slightly clunky and doesn't do absolutely everything you might want it to, but it was more important to get it solid and tested for LINQ than to make it work for a bunch of immutable collection types that largely didn't even exist.

    Had this feature been designed into the language from day one, while the frameworks types were still evolving, I'm sure that things would have gone differently. As we've discussed elsewhere on this site, I would dearly love to have a write-once-read-many fixed size array of values. It would be nice to define a common pattern for proffering up a bunch of state to initialize an arbitrary immutable collection. You are right that the collection initializer syntax would be ideal for such a thing.

    Features like that are on the list for potential future hyptothetical language versions, but not real high on the list. In other words, let's get async/await right first before we think too hard about syntactic sugars for immutable collection initialization.

提交回复
热议问题