C# Object Initializer

With object initialization, you can assign values ​​to all available fields or properties of an object during creation without having to call a constructor followed by row assignment statements. Object initialization syntax allows you to specify arguments for a constructor or omit arguments (and the syntax in parentheses).

Example:

using System;
					
public class Program
{
	public static void Main()
	{
		Subjects subjects = new Subjects() { Subject_Name = "C#", Subject_Author = "Shahzad"};

		Console.WriteLine(subjects.Subject_Name);
	}
}

public class Subjects
{
    public string Subject_Name { get; set; }
	public string Subject_Author { get; set; }

}

Output:

C#

In the above example, we have initialized the Subjects class without any constructor. In the main method, we have assigned the value of all.

Collection Initializer Syntax

We can initialize the collection with the same method which we had used in the previous example

Example:

using System;
using System.Collections.Generic;					
public class Program
{
	public static void Main()
	{
		Subjects subjects = new Subjects() { Subject_Name = "C#", Subject_Author = "Shahzad"};
        Subjects subjects1 = new Subjects() { Subject_Name = "C# Methods", Subject_Author = "Shahzad"};
       Subjects subjects2 = new Subjects() { Subject_Name = "C# Propertiese", Subject_Author = "Shahzad"};
       Subjects subjects3 = new Subjects() { Subject_Name = "C# Queue", Subject_Author = "Shahzad"};
       Subjects subjects4 = new Subjects() { Subject_Name = "C# Stack", Subject_Author = "Shahzad"};
       IList<Subjects> studentList = new List<Subjects>() {subjects,subjects1,subjects2,subjects3,subjects4 };
		foreach(var name in studentList){
		Console.WriteLine(name.Subject_Name);
		}
	}
}

public class Subjects
{
    public string Subject_Name { get; set; }
	public string Subject_Author { get; set; }

}

Output:

C#
C# Methods
C# Propertiese
C# Queue
C# Stack