This is a mirror of official site: http://jasper-net.blogspot.com/

Object Initializer in C#

| Sunday, July 31, 2011
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.

...
...

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"
     }
 };


Read more: C# Corner
QR: https://chart.googleapis.com/chart?chs=80x80&cht=qr&choe=UTF-8&chl=http://www.c-sharpcorner.com/UploadFile/hirenvisavadiya/8528/

Posted via email from Jasper-net

0 comments: