Search code examples
c#.netvisual-studioasp.net-3.5

How to initialize a list with constructor?


I have a type:

public  class Human
{
    public int Id { get; set; }
    public string Address { get; set; }
    public string Name { get; set; }
    public List<ContactNumber> ContactNumbers { get; set; }

    public Human(int id)
    {
        Id = id;
    }

    public Human(int id, string address, string name,
                 List<ContactNumber> contactNumbers) :
        this(id)
    {
        Address = address;
        Name = name;
        ContactNumbers = contactNumbers;
    }        
}

Please guide me is among best practices to use constructor with for list initialization? How to initialize a list using constructor?

Edit:

Please guide me is among best practices to use constructor with for list initialization? How to assign values to list using a constructor, so if no value passed a default will be used?

Thanks


Solution

  • Using a collection initializer

    From C# 3, you can use collection initializers to construct a List and populate it using a single expression. The following example constructs a Human and its ContactNumbers:

    var human = new Human(1, "Address", "Name") {
        ContactNumbers = new List<ContactNumber>() {
            new ContactNumber(1),
            new ContactNumber(2),
            new ContactNumber(3)
        }
    }
    

    Specializing the Human constructor

    You can change the constructor of the Human class to provide a way to populate the ContactNumbers property:

    public class Human
    {
        public Human(int id, string address, string name, IEnumerable<ContactNumber> contactNumbers) : this(id, address, name)
        {
            ContactNumbers = new List<ContactNumber>(contactNumbers);
        }
    
        public Human(int id, string address, string name, params ContactNumber[] contactNumbers) : this(id, address, name)
        {
            ContactNumbers = new List<ContactNumber>(contactNumbers);
        }
    }
    
    // Using the first constructor:
    List<ContactNumber> numbers = List<ContactNumber>() {
        new ContactNumber(1),
        new ContactNumber(2),
        new ContactNumber(3)
    };
    
    var human = new Human(1, "Address", "Name", numbers);
    
    // Using the second constructor:
    var human = new Human(1, "Address", "Name",
        new ContactNumber(1),
        new ContactNumber(2),
        new ContactNumber(3)
    );
    

    Bottom line

    Which alternative is a best practice? Or at least a good practice? You judge it! IMO, the best practice is to write the program as clearly as possible to anyone who has to read it. Using the collection initializer is a winner for me, in this case. With much less code, it can do almost the same things as the alternatives -- at least, the alternatives I gave...