With object constructors we can initialize an object and put it into an early state. There is also another way to initialize an object. An object initializer is syntax for quickly initializing an object without the need to call one of its constructors. Why would you need this? Simply to avoid creating multiple constructors. Too many constructors make the code harder to maintain.
Suppose we have a Person class with a bunch of properties. We have Id, FirstName, LastName and Birthdate. We don’t need to have constructors for each combination of properties. Note that when we call the Person class the paramterless constructor is called first, and then the code in our object initializer is called second. We can initialize it like this.
Note that all of the properties are public. There are therefore accessible from outside the class, meaning that when the consumer of the class creates and object from this class. they can gain access to the FirstName property with the syntax person.FirsstName, in our example below.
This is from Mosh Hamedani’s video called “Object Initializers” from the Udemy.com course called C# Intermediate: Classes, Interfaces and OOP.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ObjectInitializers { class Program { public class Person { public int id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public DateTime BirthDate { get; set; } } static void Main(string[] args) { var person = new Person {FirstName = "John", LastName = "Smith"}; Console.WriteLine("Last name is {0}", person.LastName); Console.ReadKey(); // OUTPUT: Last name is Smith } } }