Search code examples
c#generic-list

How do I make a list that has a primary item


I need a List of items with sharable behavior.

Example:

Person class

has List<PhoneNumber> where only one PhoneNumber is bool IsPrimary same for other items has List<EmailAddress> has List<Address>

Imagine each item (PhoneNumber, EmailAddress, Address) share the same interface ICanBePrimary which contains the requirement of one property bool IsPrimary and when in a List<ICanBePrimary> only one item in the list can have a true value for IsPrimary.


Solution

  • The cleanest approach would be to hide a list behind a class that lets you enumerate over the content, and provides additional methods for identifying the primary item:

    class AddressList : List<Address> {
        private int indexOfPrimaryAddress = 0;
        public Address PrimaryAddress {
            get {
                return this[indexOfPrimaryAddress];
            }
            set {
                indexOfPrimaryAddress = this.IndexOf(value);
            }
        }
        // Override more methods to make sure that the index does not become "hanging"
    }
    

    An even cleaner implementation would encapsulate the list inside your AddressList class, and expose only the methods that you want exposed:

    class AddressList : IList<Address> {
        private int indexOfPrimaryAddress = 0;
        private readonly IList<Address> actualList = new List<Address>();
        // Implement the List<Address> by forwarding calls to actualList
    }