Why is an Add method required for { } initialization?

前端 未结 9 2258
渐次进展
渐次进展 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:02

    It's because the initialization statement is shorthand for the CLR. When it gets compiled into bytecode, it will call the Add method you've defined.

    So you can make the case that this initialization statement is not really a "first class" feature, because it doesn't have a counterpart in IL. But that's the case for quite a lot of what we use, the "using" statement for example.

提交回复
热议问题