Two of the features from C#3 and VB 9 that I like the most are object initializers and collection initializers. In the old days before C# 3 and VB 9, when we want to create a list and add items to that list, we had to write a lot of code. For example, let’s say that we would like to create some Products and store those Products in a list, we would write something like this:
// C# Product p1 = new Product(); p1.ProductID = 1; p1.ProductName = "Lakers 2009 Championship T-Shirt"; p1.UnitPrice = 29.99; Product p2 = new Product(); p2.ProductID = 2; p2.ProductName = "Lakers 2009 Championship Banner"; p2.UnitPrice = 199.99; List<Product> products = new List<Product>(); products.Add(p1); products.Add(p2);
‘ Visual Basic
Dim p1 As New Product()
p1.ProductID = 1
p1.ProductName = “Lakers 2009 Championship T-Shirt”
p1.UnitPrice = 29.99
Dim p2 As New Product()
p1.ProductID = 2
p1.ProductName = “Lakers 2009 Championship Banner”
p1.UnitPrice = 199.99
Dim products As New List(Of Product)
products.Add(p1)
products.Add(p2)
In C# 3 and VB 9, we can use the object initializer syntax together with the collection initializer syntax to instantiate a list and add items to the list at the same time:
// C# 3
List<Product> products = new List<Product>
{
new Product { ProductID = 1, .ProductName = “Lakers 2009 Championship T-Shirt”, UnitPrice = 29.99},
new Product { ProductID = 2, .ProductName = “Lakers 2009 Championship Banner”, UnitPrice = 199.99}
}
‘ VB 9
Dim products As New List(Of Product)
{
New Product() {New Product With { .ProductID = 1, .ProductName = “Lakers 2009 Championship T-Shirt”, .UnitPrice = 29.99},
{New Product With { .ProductID = 2, .ProductName = “Lakers 2009 Championship Banner”, .UnitPrice = 199.99}
}
As you can see, the new syntax is much more concise and less verbose.
