views:

152

answers:

4

Are setters necessary 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 it suffice if I initialize a List & use readonly property Customers ? as in Company.Customers.Add(new Customer)

What is the best practice with respect to providing setters for collection Type properties?

A: 

I prefer

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

But this requries

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

in Company constructor

abatishchev
+3  A: 

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

it contains good advice :)

TheCodeJunkie
+1  A: 

Not in general (and I don't normally add them), but they are necessary if you want to use XmlSerializer. Which is a pain. It must also be a concrete type (for example List<T> or T[] - not IList<T>). Fortunately, DataContractSerializer doesn't suffer the same fate.

Marc Gravell
I'd love to know why this got downvoted... fact: XmlSerializer demands setters on collection properties. This isn't opinion, etc - try it...
Marc Gravell
A: 

As much as I like auto-implemented properties; method #2 is slightly better.

The first reason is that you can create an instance of List<> at the same place you declare the member variable, just as you've done.

The second reason is that you can mark your member variable as readonly as you've done which prevents even other private methods from replacing the list. Of course, member functions can still call customers.RemoveAll() ...

On a different note, you might also consider making your Customers property return IEnumerable until you know clients need ICollection or IList.

Dan