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
};
Not only object initializers make it easier to initialize objects but also make code look cleaner and readable.
Advertisements
By Sriramjithendra Posted in C#.NET

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s