C# Object Initializer

Summary: in this tutorial, you’ll learn about the C# object initializer to assign values to any accessible fields or properties of the object.

Introduction to the C# object initializer

An object initializer allows you to initialize accessible fields and properties of an object of a class.

First, define the Person class with three public properties and two constructors:

// Person.cs
class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public byte Age { get; set; }

    public Person() 
    {
    }

    public Person(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
}Code language: C# (cs)

Second, create a new instance of the Person class and assign values to the Firstname, LastName, and Age properties:

// Program.cs

var p1 = new Person();
p1.FirstName = "John";
p1.LastName = "Doe";
p1.Age = 25;Code language: C# (cs)

And use the second constructor to create and initialize another Person object:

// Program.cs

var p1 = new Person();
p1.FirstName = "John";
p1.LastName = "Doe";
p1.Age = 25;


var p2 = new Person("Jane", "Doe");
p2.Age = 22;Code language: C# (cs)

Instead of doing it, you can use an object initializer to create a new instance of the Person class and assign the values to the object’s properties:

var p1 = new Person
{
    FirstName = "John",
    LastName = "Doe",
    Age = 1
};Code language: C# (cs)

Also, you can combine a constructor with an object initializer. The following example calls the second constructor and assigns a value to the Age property:

var p1 = new Person("John", "Doe") { Age = 1 };Code language: C# (cs)

Using object initializers with indexers

C# allows you to use an object initializer to set an indexer in an object. Consider the following example:

First, defines the Matrix class that uses an indexer to get and set elements at a specified row and column:

// Matrix.cs
class Matrix
{
    private double[,] data;
    public Matrix(int row, int column)
    {
        data = new double[row, column];
    }

    public double this[int row, int column]
    {
        get => data[row, column];
        set => data[row, column] = value;
    }
}Code language: C# (cs)

Second, create a new instance of the Matrix class and use an object initializer to assign elements:

// Program.cs
var matrix = new Matrix(3, 3)
{
    [0, 0] = 1,
    [0, 1] = 2,
    [0, 2] = 3,
    [1, 0] = 4,
    [1, 1] = 5,
    [1, 2] = 6,
    [2, 0] = 7,
    [2, 1] = 8,
    [2, 2] = 9
};

for (int row = 0; row < 3; row++)
{
    for (int column = 0; column < 3; column++)
    {
        Console.Write($"{matrix[row, column]} ");
    }
    Console.WriteLine();
}Code language: C# (cs)

Output:

1 2 3
4 5 6
7 8 9Code language: C# (cs)

Summary

  • An object initializer to initialize accessible fields and properties of an object.
Was this tutorial helpful ?