Just being curious, I saw a two ways of creating collections in C#. For me it's just an style but maybe there's another explanation. Performance? Does this correspond to a pattern? The only thing that I can see in the example 2, it's a way to prevent an overwrite of the collection.
Example 1:
public class Employee
{
...
public List<Phone> Phones
{
get; set;
}
...
}
So. from another class
Employee employee = new Employee();
employee.Phones = this.GetPhones();
Example 2:
public class Employee
{
...
private List<Phone> colPhones;
public List<Phone> Phones
{
get
{
if(this.Phones == null)
{
this.Phones = new List<Phone>();
}
return this.Phones;
}
}
...
public void AddPhone(Phone phone)
{
this.Phones.Add(phone);
}
}
So.
Employee employee = new Employee();
List<Phone> phones = this.GetPhones();
//--> Here, I know I can use for(int i....) instead of foreach. This is just for the example.
foreach(Phone phone in phones)
{
employee.Phones.Add(phone);
}
UPDATE:
I found this link Encapsulate collection when I was reading a Martin Fowler's book named "Refactoring" which is the same concept as the accepted answer.
In my opinion your first example is a rather dangerous. You say yourself that it is vulnerable to an "overwrite" of the collection, but I think even more important it is vulnerable to subtle modifications of the collection if you aren't very careful.
Employee employee = new Employee();
List<Phone> obscureTemporaryVariable = this.GetPhones();
employee.Phones = obscureTemporaryVariable;
...
// much later, after having forgotten all about the above bit of code
obscureTemporaryVariable.Clear();
obscureTemporaryVariable.Add(new Phone(42));
Now you've (presumably unintendedly) modified the phone numbers for "employee".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With