C# Object Initializer Syntax


What is an Object Initializer in C#? Object initializers are the easiest way to assign values of an object’s properties and fields. An object can be initialized without explicitly calling a class’s constructor. In other words, object initializers allow you to assign values to the fields or properties at the time of creating an object without invoking a constructor. We have another post at BCN called C# Collection Initializer Syntax.

C# 3.0 (.NET 3.5) introduced Object Initializer Syntax, a new way to initialize an object of a class or collection.

Here is our C# console program.

using System;
namespace ObjectInitializerSyntax
{
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int AgeInYears { get; set; }
        public int Number { get; set; }
        public Person()  // default constructor
        {
            Id = 1;
            Name = "Sally";
            AgeInYears = 1;
            // Number is not initialized here
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            // NOT using object initializer syntax here
            Person p = new Person();
            p.Id = 1;
            p.Name = "Bob";
            // p.AgeInYears is not set, so the constructor value is used.
            // p.Number is not set, not set in constructor, so default value of zero

            Person p2 = new Person();  // constructor sets all values except Number, which gets 0

            Person p3 = new Person
            {   // object initializer syntax:
                Id = 3,
                Name = "John",
                AgeInYears = 33,
                Number = 333
            };
            Person p4 = new Person
            {   // object initializer syntax:
                Id = 4,
                Name = "Forth"
                // you do not have to initialize all properties.
                // the constructor still sets AgeInYears to 1
            };
            Console.WriteLine("Hi {0}! You are {1} years old. Number: {2}", p.Name, p.AgeInYears, p.Number);
            Console.WriteLine("Hi {0}! You are {1} years old. Number: {2}", p2.Name, p2.AgeInYears, p2.Number);
            Console.WriteLine("Hi {0}! You are {1} years old. Number: {2}", p3.Name, p3.AgeInYears, p3.Number);
            Console.WriteLine("Hi {0}! You are {1} years old. Number: {2}", p4.Name, p4.AgeInYears, p4.Number);
        }
    }
}

Here is the output.

Hi Bob! You are 1 years old. Number: 0
Hi Sally! You are 1 years old. Number: 0
Hi John! You are 33 years old. Number: 333
Hi Forth! You are 1 years old. Number: 0
Press any key to continue . . .