Object initializer
In the past we couldn't initialize an object without using a constructor. For example, we could create and initialize a Product
object like this if the Product
class had a constructor with three parameters:
Product p = new product(1, "first candy", 100.0);
Or we could create the object and then initialize it later, like this:
Product p = new Product(); p.ProductID = 1; p.ProductName = "first candy"; p.UnitPrice=(decimal)100.0;
Now with the new object initializer feature we can do it as follows:
Product product = new Product { ProductID = 1, ProductName = "first candy", UnitPrice = (decimal)100.0 };
At compile time the compiler will automatically insert the necessary property setter code. So again this new feature is a Visual Studio compiler feature. The compiled assembly is actually a valid .NET 2.0 assembly.
We can also define and initialize a variable with an array, like this:
var arr = new[] { 1, 10, 20, 30 };
This...