Lambda expressions and extension methods provide us with everything we need for queries that simply filter members out of a sequence of values. Most query expressions also perform projection over those members, effectively transforming members of the original sequence into members whose value and type may differ from the original. To support writing these transforms, LINQ relies on a new construct called object initializers to create new instances of structured types. For the rest of this document, we'll assume the following type has been defined:
public class Person {
string name;
int age;
bool canCode;
public string Name {
get { return name; } set { name = value; }
}
public int Age {
get { return age; } set { age = value; }
}
public bool CanCode {
get { return canCode; } set { canCode = value; }
}
}
Object initializers allow us to easily construct values based on the public fields and properties of a type. For example, to create a new value of type Person, we can write this statement:
Person value = new Person {
Name = "Chris Smith", Age = 31, CanCode = false
};
Semantically, this statement is equivalent to the following sequence of statements:
Person value = new Person();
value.Name = "Chris Smith";
value.Age = 31;
value.CanCode = false;
Object initializers are an important feature for language-integrated query, as they allow the construction of new structured values in contexts where only expressions are allowed (such as within lambda expressions and expression trees). For example, consider this query expression that creates a new Person value for each value in the input sequence:
IEnumerable<Person> query = names.Select(s => new Person {
Name = s, Age = 21, CanCode = s.Length == 5
});
Object initialization syntax is also convenient for initializing arrays of structured values. For example, consider this array variable that is initialized using individual object initializers:
static Person[] people = {
new Person { Name="Allen Frances", Age=11, CanCode=false },
new Person { Name="Burke Madison", Age=50, CanCode=true },
new Person { Name="Connor Morgan", Age=59, CanCode=false },
new Person { Name="David Charles", Age=33, CanCode=true },
new Person { Name="Everett Frank", Age=16, CanCode=true },
};