[フレーム]

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. publicclass Customer
  2. {
  3. privateint _customerID;
  4. privatestring _companyName;
  5. private Phone _phone;
  6. publicint CustomerID
  7. {
  8. get { return _customerID; }
  9. set { _customerID = value; }
  10. }
  11. publicstring 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. publicclass Phone
  23. {
  24. privatestring _countryCode;
  25. publicstring CountryCode
  26. {
  27. get { return _countryCode; }
  28. set { _countryCode = value; }
  29. }
  30. privatestring _areacode;
  31. publicstring AreaCode
  32. {
  33. get { return _areacode; }
  34. set { _areacode = value; }
  35. }
  36. privatestring _phonenumber;
  37. publicstring 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!

People also reading
Membership not found

AltStyle によって変換されたページ (->オリジナル) /