.NET Framework Collections Creating an initialized List with Custom Types

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

public class Model
{
    public string Name { get; set; }
    public bool? Selected { get; set; }
}

Here we have a Class with no constructor with two properties: Name and a nullable boolean property Selected. If we wanted to initialize a List<Model>, there are a few different ways to execute this.

var SelectedEmployees = new List<Model>
 {
      new Model() {Name = "Item1", Selected = true},
      new Model() {Name = "Item2", Selected = false},
      new Model() {Name = "Item3", Selected = false},
      new Model() {Name = "Item4"}
 };

Here, we are creating several new instances of our Model class, and initializing them with data. What if we added a constructor?

public class Model
{

    public Model(string name, bool? selected = false)
    {
        Name = name;
        selected = Selected;
    }
    public string Name { get; set; }
    public bool? Selected { get; set; }
}

This allows us to initialize our List a little differently.

var SelectedEmployees = new List<Model>
{
    new Model("Mark", true),
    new Model("Alexis"),
    new Model("")
};

What about a Class where one of the properties is a class itself?

public class Model
{
    public string Name { get; set; }
    public bool? Selected { get; set; }
}

public class ExtendedModel : Model
{
    public ExtendedModel()
    {
        BaseModel = new Model();
    }

    public Model BaseModel { get; set; }
    public DateTime BirthDate { get; set; }
}

Notice we reverted the constructor on the Model class to simplify the example a little bit.

var SelectedWithBirthDate = new List<ExtendedModel>
{
    new ExtendedModel()
    {
        BaseModel = new Model { Name = "Mark", Selected = true},
        BirthDate = new DateTime(2015, 11, 23)
    },
                    new ExtendedModel()
    {
        BaseModel = new Model { Name = "Random"},
        BirthDate = new DateTime(2015, 11, 23)
    }
};

Note that we can interchange our List<ExtendedModel> with Collection<ExtendedModel>, ExtendedModel[], object[], or even simply [].



Got any .NET Framework Question?