Setters for collection type properties

Are setters required for collection type properties?

//Type 1    
class Company
{
    private IList<Customer> customers;

    public IList<Customer> Customers
    {
        get { return customers; }
        set { customers = value; }
    }
}

 //Type 2 
 class Company
 {
       private readonly IList<Customer> customers = new List<Customer>();

       public IList<Customer> Customers
       {
               get { return customers; }
       }
  }

When do I use Type 1 vs Type 2? Wouldn't that be if I initialized the List and used readonly client properties? how inCompany.Customers.Add(new Customer)

What is the best practice regarding providing setters for collection type properties?

+4
source share
3 answers

Please read FxCop recommendation CAS2227 "Collection properties should only be read" http://msdn.microsoft.com/en-us/library/ms182327(VS.80).aspx

contains good advice :)

+3
source

( ), , XmlSerializer. . (, List<T> T[] - not IList<T>). , DataContractSerializer .

+2

I prefer

public IList<Customer> Customers { get; private set; }

But these requirements

this.Customers = new List<Customer>();

in the Companyconstructor

0
source

All Articles