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.
- publicclass Customer
- {
- privateint _customerID;
- privatestring _companyName;
- private Phone _phone;
- publicint CustomerID
- {
- get { return _customerID; }
- set { _customerID = value; }
- }
- publicstring CompanyName
- {
- get { return _companyName; }
- set { _companyName = value; }
- }
- public Phone Phone
- {
- get { return _phone; }
- set { _phone = value; }
- }
- }
- publicclass Phone
- {
- privatestring _countryCode;
- publicstring CountryCode
- {
- get { return _countryCode; }
- set { _countryCode = value; }
- }
- privatestring _areacode;
- publicstring AreaCode
- {
- get { return _areacode; }
- set { _areacode = value; }
- }
- privatestring _phonenumber;
- publicstring AreaCode
- {
- get { return _phonenumber; }
- set { _phonenumber = value; }
- }
- }
Regular method of initializing an instance of the Customer class.
- Phone oPhone = new Phone();
- oPhone.CountryCode = "+91";
- oPhone.AreaCode = "0999";
- oPhone.PhoneNumber = "999999";
- Customer oCustomer = new Customer();
- oCustomer.CustomerID = 101;
- oCustomer.CompanyName = "oTest Corporation";
- oCustomer.Phone = oPhone;
By taking advantage of Object Initializers an instance of the Customer class
- Customer nCustomer = new Customer()
- {
- CustomerID = 102,
- CompanyName = "nTest Corporation",
- Phone = new Phone()
- {
- CountryCode = "+91",
- AreaCode = "09999",
- PhoneNumber = "999999"
- }
- };
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!