Object Initializer in C#

Object initializers is the easiest and fastest way to assign values of an object's properties and fields. An object can be initialized without explicitly calling a class's constructor. 

The following code snippet lists an Author class with some public properties. 

public class Author
{
    public string Name { get; set; }
    public string Book { get; set; }
    public string publisher { get; set;}
    public Int16 Year { get; set; }
    public double Price { get; set; }
}

In a typical behavior, we will create the Author class object using the constructor and set its properties values in the following way.

 Author mahesh = new Author();
mahesh.Name = "Mahesh Chand";
mahesh.Book = "LINQ Programming";
mahesh.publisher = "APress";
mahesh.Year = 2013;
mahesh.Price = 49.95;

By using the object initializers, we can pass the public properties values during when we are creating the object without explicitly invoking the Author class constructor. The following code does the trick. 

 Author mahesh = new Author()
{
    Name = "Mahesh Chand", 
    Book = "LINQ Programming",
    publisher = "APress",
    Year = 2013,
    Price = 49.95
};

This may not sound as useful right now but when you're dealing with complex queries in LINQ, the object initializers make developer's lives much easier. Not only object initializers make it easier to initialize objects but also make code look cleaner and readable. 

Up Next
    Ebook Download
    View all
    Learn
    View all