Object/Collection Initializer in C#

Let us play around with some new features of C# 3.0 or above and you can say .Net framework 3.0 and above, like Object initializer, implicitly typed variables, extension methods, anonymous types, object initializer, Collection initializer, and automatic properties.

Let's start with Object and collection initializes.

Just refer to the following code of style. Definitely all .Net coders are aware of these lines.

  1. public class Customer  
  2. {  
  3.     private int _customerID;  
  4.     private string _companyName;  
  5.     private Phone _phone;  
  6.     public int CustomerID  
  7.     {  
  8.         get { return _customerID; }  
  9.         set { _customerID = value; }  
  10.     }  
  11.     public string CompanyName  
  12.     {  
  13.         get { return _companyName; }  
  14.         set { _companyName = value; }  
  15.     }  
  16.     public Phone Phone  
  17.     {  
  18.         get { return _phone; }  
  19.         set { _phone = value; }  
  20.     }  
  21. }  
  22.   
  23. public class Phone  
  24. {  
  25.     private string _countryCode;  
  26.     public string CountryCode  
  27.     {  
  28.         get { return _countryCode; }  
  29.         set { _countryCode = value; }  
  30.   
  31.     }  
  32.     private string _areacode;  
  33.     public string AreaCode  
  34.     {  
  35.         get { return _areacode; }  
  36.         set { _areacode = value; }  
  37.     }  
  38.     private string _phonenumber;  
  39.     public string AreaCode  
  40.     {  
  41.         get { return _phonenumber; }  
  42.         set { _phonenumber = value; }  
  43.     }  
  44.   

Regular method of initializing an instance of the Customer class.

  1. Phone oPhone = new Phone();  
  2. oPhone.CountryCode = "+91";  
  3. oPhone.AreaCode = "0999";  
  4. oPhone.PhoneNumber = "999999";  
  5.   
  6. Customer oCustomer = new Customer();  
  7. oCustomer.CustomerID = 101;  
  8. oCustomer.CompanyName = "oTest Corporation";  
  9. oCustomer.Phone = oPhone;
By taking advantage of Object Initializers an instance of the Customer class
  1. Customer nCustomer = new Customer()  
  2. {  
  3.      CustomerID = 102,  
  4.      CompanyName = "nTest Corporation",  
  5.      Phone = new Phone()  
  6.      {  
  7.          CountryCode = "+91",  
  8.          AreaCode = "09999",  
  9.          PhoneNumber = "999999"  
  10.      }  
  11. }; 

We do not need to take care of performance issues. Because in the execution time, both samples make sample IL code. So both samples give sample performance.

Next time we will look into automatic property.

Happy coding!


Similar Articles