Anonymous type syntax without explicit keys (`new {identifier}`)?

In this question, I saw an anonymous type expression with an unknown syntax:

new { MyObjectID = g.Key, totalSum } 

At first I thought that this ( , totalSum } ) is a syntax error, because the key is not specified, but it compiles and works in C # 3.0. I checked this syntax in LINQPad (2.x -> C # 3):

 var y = ":-)"; var q = new { Y = y, y, y.Length, }; q.Dump(); 

Result:

 (anon type) { Y = ":-)", y = ":-)", Length = 3 } 

Where in the specification is this syntax specified? (Responses should include the applicable link and related excerpt).

And, more subjectively (feel free to answer), is this a good syntax / short cut to omit the keys? I did not use it until I knew about it, and I am not very in love with this syntactic sugar.

+4
source share
2 answers

7.6.10.6 Expressions of anonymous creation of objects

A participant's declaration may be abbreviated to a simple name (Β§7.5.2), member access (Β§7.5.4) or basic access (Β§7.6.8). This is called the projection initializer and is short for declaring and assigning a property with the same name. In particular, the declarators of the participants in the form

 identifier expr . identifier 

exactly equivalent as follows:

 identifer = identifier identifier = expr . identifier 

Thus, in the projection, the Initializer selects the identifier of both the value and the field or property whose value is assigned. Intuitively, the project initializer projection is not just a value, but also a name for the value.

(p. 181)

In simple terms, this means that if you yourself do not provide an identifier, the compiler will select the identifier for the "last" member of the default expression.

As for if it is good or bad ... well, I would not do it for sure to exclude the possibility that someone who does not know this shortcut is confused.

+8
source

Not sure about C # -3.0, but a link to C # -4.0 is discussed in Section 7.6.10.6 Anonymous object creation expressions .

An anonymous object initializer declares an anonymous type and returns an instance of this type. An anonymous type is an unnamed class type that inherits directly from an object. Elements of an anonymous type are a series of read-only properties derived from the initializer of an anonymous object used to instantiate this type.

I saw anonymous types commonly used in ASP.Net MVC for things like passing arbitrary HTML attributes to the Html Helper method.

+2
source

Source: https://habr.com/ru/post/918695/


All Articles