logo search
CSharp_Prog_Guide

Результат

Third's destructor is called

Second's destructor is called

First's destructor is called

Object and Collection Initializers

Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor. The following example shows how to use an object initializer with a named type. Note the use of auto-implemented properties in the Test class.

private class Cat

{

// Auto-implemented properties

public int Age { get; set; }

public string Name { get; set; }

}

static void MethodA()

{

// Object initializer

Cat cat = new Cat { Age = 10, Name = "Sylvester" };

}

Object Initializers with anonymous types

Although object initializers can be used in any context, they are especially useful in LINQ query expressions. Query expressions make frequent use of anonymous types, which can only be initialized with an object initializer. In the select clause, a query expression can transform objects of the original sequence into objects whose value and shape may differ from the original. This is very useful if you want to store only a part of the information in each object in a sequence. In the following example, assume that a product object (p) contains many fields and methods, and that you are only interested in creating a sequence of objects that contain the product name and the unit price.

var productInfos =

from p in products

select new { p.ProductName, p.UnitPrice };

When this query is executed, the productInfos variable will contain a sequence of objects that can be accessed in a foreach statement as shown in this example:

foreach(var p in productInfos){...}

Each object in the new anonymous type has two public properties which receive the same names as the properties or fields in the original object. You can also rename a field when you are creating an anonymous type; the following example renames the UnitPrice field to Price.

select new {p.ProductName, Price = p.UnitPrice};