Object Initializers And Collection Initializers - A Syntactic Sugar In C# 3.0

Introduction

Object initializers and Collection initializers are part of C# 3.0.These two concepts add a flexibility, readability, and maintainability in C#. As we are C# developers, we should know how and in which situations we can use these two concepts and inprove our programming logic. Before going deep, dive into object and collection initializers. We will check what are these Syntactic Sugars.

Syntactic sugar in programming 

Syntactic sugar, or syntax sugar, is considered as a "shortcut" provided by the language, which reduces the amount of code that must be written in a particular situation.

Syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an alternative style that some may prefer.

 

The main benifits of using syntatic sugar in programming are-

  1. Avoid lot of keystrokes,The efficiency of software programs is sometimes measured by the number of keystrokes it requires to write a specific function.
  2. Easy to readable and maintainable.
  3. Time saving approach.
Let's see an example of  how we can use syntactic sugar in our program. Let's consider an example of normal IF-ELSE conditional statement.
  1. class Program  
  2.     {  
  3.          
  4.   
  5.         static void Main(string[] args)  
  6.         {  
  7.              int x = 20, y = 10;  
  8.             if (x>y)  
  9.             {  
  10.                 Console.WriteLine(x);  
  11.                   
  12.             }  
  13.             else  
  14.             {  
  15.                 Console.WriteLine(y);  
  16.   
  17.             }  
  18.             Console.ReadLine();  
  19.   
  20.         }  
Now, let's use Ternary operators and see how much key strokes we can prevent using Ternary operator.
  1. class Program  
  2.     {  
  3.         static void Main(string[] args)  
  4.         {  
  5.             int x = 20, y = 10;  
  6.             var result = x > y ? x : y;  
  7.             Console.WriteLine(result);  
  8.             Console.ReadLine();  
  9.   
  10.         }  

So, in this way, we can say that by using ternary operator, we can achive syntactic sugar in our programming. Now, let's come to our main topic about Object Initialization and Collection Initialization.

So in programming, initialization is the assignment of an initial value for a data object or variable.

Object Initializers 

Before going toward object initializers, let us see how we are initialising a object in C# 2.0.
  1. namespace syntax_sugar  
  2. {  
  3.    public  class Employee  
  4.     {  
  5.         public string Name { get; set; }  
  6.         public int Id { get; set; }  
  7.         public string Department { get; set; }  
  8.         public int salary { get; set; }  
  9.     }  
  10.     class Program  
  11.     {  
  12.         static void Main(string[] args)  
  13.         {  
  14.             Employee emp=new Employee();  
  15.             emp.Name = "Kumar";  
  16.             emp.Department = "IT";  
  17.             emp.Id = 101;  
  18.             emp.salary = 80000;  
  19.             Console.ReadLine();  
  20.   
  21.         }  
  22.     }  

Let's see how we can do that using object initializer in C# 3.0.

Write the same program using Object Initializer.

  1. class Program  
  2.     {  
  3.         static void Main(string[] args)  
  4.         {  
  5.             Employee emp = new Employee {Name = "Kisan",Id = 55,Department = "IT",salary = 20000};  
  6.   
  7.   
  8.         }  
  9.     }  
It seems that we have saved a lot of Key strokes using this Object Initializer. So, this is also considered as a "Syntactic Sugar".
 
Collection Initializers
 
Collection Initializers are used to initialize a collection in a planned and advance manner to avoid lot of Key strokes.
  1. namespace syntax_sugar  
  2. {  
  3.    public  class Employee  
  4.     {  
  5.         public string Name { get; set; }  
  6.         public int Id { get; set; }  
  7.         public string Department { get; set; }  
  8.         public int salary { get; set; }  
  9.     }  
  10.     class Program  
  11.     {  
  12.         static void Main(string[] args)  
  13.         {  
  14.               
  15.            List<Employee> liemp=new List<Employee>();  
  16.             Employee emp = new Employee();  
  17.             emp.Name = "Kumar";  
  18.             emp.Department = "IT";  
  19.             emp.Id = 101;  
  20.             emp.salary = 80000;  
  21.             liemp.Add(emp);   //one object is added in the list  
  22.   
  23.             Employee emp1 = new Employee();  
  24.             emp1.Name = "Abdul";  
  25.             emp1.Department = "IT";  
  26.             emp1.Id = 1010;  
  27.             emp1.salary = 80000;  
  28.             liemp.Add(emp1);    //Second object is added in the List  
  29.   
  30.         }  
  31.     }  
Let's see how we can improve our coading quality using collection Initializers. Consider the following program for reference.
  1. static void Main(string[] args)  
  2.         {  
  3.   
  4.             List<Employee> liemp = new List<Employee>  
  5.             {  
  6.                 new Employee {Name = "Kumar",Id = 101,Department = "IT",salary = 80000},  
  7.                 new Employee {Name = "Abdul",Id = 1010,Department = "IT",salary = 80000}  
  8.   
  9.   
  10.             };  
  11.        
  12.         }  

Similarly, we can initialize for all collection. Let us see how we can initialize a dictionary.

  1. Dictionary<int,string> dict = new Dictionary<int,string>();  
  2.             dict.Add(1,"Mohan");  
  3.             dict.Add(2, "Kishor");  
  4.             dict.Add(3, "Pankaj");  
  5.             dict.Add(4, "Jeetu");  
We can write a shortcut initialization as follow.
  1.  Dictionary<int,string> dict = new Dictionary<int,string>  
  2.             {  
  3.   
  4.                 {1,"Mohan" },  
  5.                 {2,"Kishor" },  
  6.                 {3,"Pankaj" },  
  7.                 {4,"Jeetu" }  
  8.   
  9.             };  
Conclusion 

Here, our main intention is to make you aware about Collection Initialization and Object Initiallization which are two important concepts discovered in C# 3.0, and let you know how these two important concepts are considered as syntactic sugar in progromming.

Hope you liked this article. If you have any doubts  and suggestation, please do comment so that I can update


Similar Articles