Object Initializer in C#

Introduction

Object initializers are the easiest and fastest way to assign values to 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 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 do object initializers make it easier to initialize objects but also make code look cleaner and readable.


Recommended Free Ebook
Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.