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:

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 2008 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 array is called an implicitly typed array.

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

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