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. 
  1. public class Author  
  2. {  
  3.     public string Name { getset; }  
  4.     public string Book { getset; }  
  5.     public string publisher { getset;}  
  6.     public Int16 Year { getset; }  
  7.     public double Price { getset; }  
  8. }  
In a typical behavior, we will create the Author class object using the constructor and set its properties values in the following way.
  1. Author mahesh = new Author();  
  2. mahesh.Name = "Mahesh Chand";  
  3. mahesh.Book = "LINQ Programming";  
  4. mahesh.publisher = "APress";  
  5. mahesh.Year = 2013;  
  6. 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. 
  1. Author mahesh = new Author()  
  2. {  
  3.     Name = "Mahesh Chand",   
  4.     Book = "LINQ Programming",  
  5.     publisher = "APress",  
  6.     Year = 2013,  
  7.     Price = 49.95  
  8. };  
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. 

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.