Object and Collection Initializers in C#

Leave a Comment

Initializers provide an easy way to initialize an object when a multi parameter constructor is not available e.g., in the previous example of Product class, if one wanted to initialize an object of the Product class, they will need to write the following code.
Product pr = new Product();
pr.ProductId = 1234;
pr.CatId = 10;
pr.ProductSDesc = "Calculator";
pr.ProductImage = "calcss.jpg";
pr.ProductLDesc = "Sharp Solar Powered Scientific Calculator";
pr.Price = 21.50m;
pr.InStock = true;
pr.Inventory = 15;

Alternatively, one could write a single statement using the initializer capability as:
//---------object creation with initializer capability
Product pr2 = new Product
{
ProductId = 1234, CatId = 10, ProductSDesc = "Calculator", ProductImage = "calcss.jpg",
 ProductLDesc = "Sharp Solar Powered Scientific Calculator",
 Price = 21.50m, InStock = true, Inventory = 15 };

As you can see the initializer capability allows us to initialize an object with many parameters as if a corresponding constructor was available.

Similarly Collection initializers can initialize a collection like an array e.g.,
//----------Collection Initializer-------
List<int> Scores = new List<int> { 85, 98, 91 };
List<ProductInfoShort> PList = new List<ProductInfoShort>
{new ProductInfoShort{ProductId=1235,
ProductSDesc="Calculator",Price=24.50m},
new ProductInfoShort{ProductId=1235,
ProductSDesc="Calculator",Price=24.50m}};
MessageBox.Show("PList Count = " + PList.Count.ToString());

The above code assumes that there is a class called ProductInfoShort that has three properties i.e., ProductId, ProductSDesc, and Price in it.

0 comments:

Post a Comment