Empty collection initializer for list property results in null

后端 未结 1 699
-上瘾入骨i
-上瘾入骨i 2021-01-21 21:37

When I run this code, it doesn\'t initialize ThisIsAList to an empty collection as I was expecting... instead ThisIsAList was null.

voi         


        
相关标签:
1条回答
  • 2021-01-21 22:12

    In section 7.6.10.2 of the C# 5.0 specs:

    A member initializer that specifies a collection initializer after the equals sign is an initialization of an embedded collection. Instead of assigning a new collection to the field or property, the elements given in the initializer are added to the collection referenced by the field or property. The field or property must be of a collection type that satisfies the requirements specified in §7.6.10.3.

    (emphasis mine)

    So since your collection initializer is nested inside of another object/collection initializer the behavior is that it resolves the member it is initialzing to a value, and then adds the relevant items. In this case, the property is null, so that null value is resolved, and all zero items in your initializer are added. If you actually tried to add an item, it'd throw a NRE since you'd be trying to add an item to a null object.

    0 讨论(0)
提交回复
热议问题