Anonymous object creation expressions
An anonymous-object-creation-expression is used to create an object of an anonymous type. anonymous-object-creation-expression: anonymous-object-initializer: member-declarator-list: member-declarator: An anonymous object initializer declares an anonymous type and returns an instance of that type. An anonymous type is a nameless class type that inherits directly from object. The members of an anonymous type are a sequence of read-only properties inferred from the anonymous object initializer used to create an instance of the type. Specifically, an anonymous object initializer of the form new { p1 = e1, p2 = e2, … pn = en } declares an anonymous type of the form class __Anonymous1 public __Anonymous1(T1 a1, T2 a2,…, Tn an) { public T1 p1 { get { return f1; } } public override bool Equals(object __o) { … } where each Tx is the type of the corresponding expression ex. The expression used in a member-declarator must have a type. Thus, it is a compile-time error for an expression in a member-declarator to be null or an anonymous function. It is also a compile-time error for the expression to have an unsafe type. The names of an anonymous type and of the parameter to its Equals method are automatically generated by the compiler and cannot be referenced in program text. Within the same program, two anonymous object initializers that specify a sequence of properties of the same names and compile-time types in the same order will produce instances of the same anonymous type. In the example var p1 = new { Name = "Lawnmower", Price = 495.00 }; the assignment on the last line is permitted because p1 and p2 are of the same anonymous type. The Equals and GetHashcode methods on anonymous types override the methods inherited from object, and are defined in terms of the Equals and GetHashcode of the properties, so that two instances of the same anonymous type are equal if and only if all their properties are equal. A member declarator can be abbreviated to a simple name (§7.5.2), a member access (§7.5.4) or a base access (§7.6.8). This is called a projection initializer and is shorthand for a declaration of and assignment to a property with the same name. Specifically, member declarators of the forms identifier expr. identifier are precisely equivalent to the following, respectively: identifer = identifier identifier = expr. identifier Thus, in a projection initializer the identifier selects both the value and the field or property to which the value is assigned. Intuitively, a projection initializer projects not just a value, but also the name of the value.
|