Object initialization syntax

Initializers in C# help us combine the creation of objects and set their properties. Let's refer to the following code example. Let's assume we have a Student class that has the following declaration:

public class Student
{
public int rollNum { get; set; }
public string Name { get; set; }
}

Now, suppose we need to declare an object for this class. In a conventional way, without the use of object initializers, we can do it in the following manner:

Student p = new Student();
p.rollNum = 1;
p.Name = "James";
Student p2 = new Student();
p2.rollNum = 2;
p2.Name = "Donohoe";

Note that in the preceding code, we have to specify the creation of the p and p2 objects and set up their respective properties separately. 

Using object initialization syntax, we will be able to combine the creation of the object and the setting up of its properties in one statement. As an example, if we use object initialization to execute the same functionality that we did earlier, we can use the following syntax:

// Creating and initializing a new object in a single step
Person p = new Person
{
FirstName ="James",
LastName = "Doe"
};

Please note that even though usage of object initialization is not necessary and doesn't provide any additional capability or feature to us, it can improve the readability of our code. The code can also be enhanced if there is a requirement for creating a collection of the same objects. The following is the syntax for this:

var students = new List<Student>
{
new Student
{
rollNum = 1,
Name = "James"
},
new Student
{
rollNum = 2,
Name = "Donohoe"
}
};

Note that object initialization syntax makes the code much more readable and, in cases where we are working with anonymous types, it is actually required. In the next section, we will look at lambda expressions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.74.25