With the help of Object Initializers, you can initialize objects with fewer lines of code.
For. e.g:
We have a class representing a Student.
For. e.g:
We have a class representing a Student.
public class Student { public string StudentName; public int StudentID; public Student(string StudentName, int StudentID) { this.StudentName = StudentName; this.StudentID = StudentID; } public Student(int StudentID) { this.StudentID = StudentID; } public Student() { } }
Suppose we make a class for Student List and inherit it from class List. To add objects to this class, we'll make use of object initialization.
Before we had object initialization, we would have had to do the following:
public void Add(string StudentName, int StudentID) { Student std = new Student(StudentName, StudentID); this.Add(std); }
With object initialization, the code can be reduced to the following lines:
public void Add(string StudentName, int StudentID) { this.Add(new Student { StudentID = StudentID, StudentName = StudentName}); }
Do note that the resulting IL Code of both the above code snippets will be the same. However, you can see the difference in the lines of code the developer will need to type. Though, this may not sound very beneficial by looking at the above example. But try implementing object initialization in real-life code and you'll see the benefit.
The above example used object initialization without constructor. Here's how you use it with constructor.
public void AddStudent2(string StudentName, int StudentID) { this.Add(new Student(StudentName, StudentID)); }Another way to use object initialization is by calling the constructor and initializing the properties at the same time:
public void AddStudent(string StudentName, int StudentID) { this.Add(new Student(StudentID) { StudentName = StudentName }); }