Search code examples
c#propertiesicollection

Setting the Value of an ICollection Property in C#


My class inherits an interface so I need to have the emailaddress property in the Person class.

My question is what is the best way to get the property and set the property

public class Contact : IPerson, ILocation
{
  ...
  [MaxLength(256)]
  public string EmailAddress { 
  get{
    return this.Emails.First().ToString();
  } 
  set{ ????  }
  }
  ....

  public virtual ICollection<Emails> Emails { get; set; }
}

Essentially, I'm trying to get the class to allow more than one email.

For full disclosure, I'm pretty new to this and I may not be asking the correct questions, but I've searched for a day and half and haven't seen anything like this (not that I think it's unusual) and could use the insight.

Email class properties:

[Key]
public int Id { get; set; }

[MaxLength(256)]
    public string EmailAddress { get; set; }

Solution

  • Do you have control over the design of the IPerson interface that is forcing you to implement EmailAddress? If so, I would recommend rethinking the design to avoid needing both a singular property and a list of email addresses on the same object.

    You may also want to consider making the Emails property setter protected, to prevent outside code from changing your object's data.

    If you must implement to this interface, and you wish to have the EmailAddress property always refer to the first email in the collection, you can try this code.

    public class Contact : IPerson, ILocation
    {
      public Contact()
      {
        // Initialize the emails list
        this.Emails = new List<Emails>();
      }
    
      [MaxLength(256)]
      public string EmailAddress
      { 
        get
        {
          // You'll need to decide what to return if the first email has not been set.
          // Replace string.Empty with the appropriate value.
          return this.Emails.Count == 0 ? string.Empty : this.Emails[0].ToString();
        } 
        set
        {
          if (this.Emails.Count == 0)
          {
            this.Emails.Add(new Emails());
          }
          this.Emails[0].EmailAddress = value;
        }
      }
    
      public virtual IList<Emails> Emails { get; set; }
    }