Why can I use a collection initializer with private set access from another class?

Your statement works because the collection initialization syntax uses the Add() method to add the items to the collection rather than setting the member to a new instance of a collection. Essentially, your code is the equivalent of:

var order = new Order();
order.Items.Add(new OrderItem());
order.Items.Add(new OrderItem());

Which is fine since you only ever use the getter method.

Leave a Comment