Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ways of adding elements to collections

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.

like image 645
Maximus Decimus Avatar asked Nov 20 '25 13:11

Maximus Decimus


1 Answers

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".

like image 50
RenniePet Avatar answered Nov 22 '25 02:11

RenniePet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!