Object and Collection Initializers
Set properties at creation time concisely.
What Is an Object Initializer?
An object initializer sets public properties or fields right after new, inside { }, without writing a constructor for each combination.
using System;
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
var p = new Person { Name = "Ada", Age = 36 };
Console.WriteLine(p.Name + ", " + p.Age);
}
}Initializer Syntax
List property assignments separated by commas inside the braces. They run after the constructor completes.
using System;
class Car
{
public string Make { get; set; }
public string Model { get; set; }
public int Year { get; set; }
}
class Program
{
static void Main()
{
var car = new Car
{
Make = "Toyota",
Model = "Corolla",
Year = 2022
};
Console.WriteLine(car.Year + " " + car.Make + " " + car.Model);
}
}All lessons in this course
- Defining Constructors
- Constructor Chaining with this
- Object and Collection Initializers
- Static Constructors