Collection initializer

Similar to the object initializer, we can also initialize a collection when we declare it, like this:

List<Product> products = new List<Product> {
new Product {
ProductID = 1,
ProductName = "first candy",
UnitPrice = (decimal)10.0 },
new Product {
ProductID = 2,
ProductName = "second candy",
UnitPrice = (decimal)35.0 },
new Product {
ProductID = 3,
ProductName = "first vegetable",
UnitPrice = (decimal)6.0 },
new Product {
ProductID = 4,
ProductName = "second vegetable",
UnitPrice = (decimal)15.0 },
new Product {
ProductID = 5,
ProductName = "third product",
UnitPrice = (decimal)55.0 }
};

Here, we created a list and initialized it with five new products. For each new product, we used the object initializer to initialize its value.

Just as with the object initializer, this new feature collection initializer is also a Visual Studio 2008 compiler feature, and compiled assembly is valid .NET 2.0 assembly.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset