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. public class Phone
  23. {
  24. private string _countryCode;
  25. public string CountryCode
  26. {
  27. get { return _countryCode; }
  28. set { _countryCode = value; }
  29. }
  30. private string _areacode;
  31. public string AreaCode
  32. {
  33. get { return _areacode; }
  34. set { _areacode = value; }
  35. }
  36. private string _phonenumber;
  37. public string AreaCode
  38. {
  39. get { return _phonenumber; }
  40. set { _phonenumber = value; }
  41. }
  42. }

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. Customer oCustomer = new Customer();
  6. oCustomer.CustomerID = 101;
  7. oCustomer.CompanyName = "oTest Corporation";
  8. 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!