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
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:
Specializing the
HumanconstructorYou can change the constructor of the
Humanclass to provide a way to populate theContactNumbersproperty: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…