Search code examples
c#syntaxanonymous-types

What is a third syntax for declaring a property inside an anonymous?


What is a third syntax for declaring a property inside an anonymous?

I am reading the CLR via C# book. And I come across the following excerpt (1):

The compiler supports two additional syntaxes for declaring a property inside an anonymous type where it can infer the property names and types from variables:

String Name = "Grant";
DateTime dt = DateTime.Now;
// Anonymous type with two properties
// 1. String Name property set to Grant
// 2. Int32 Year property set to the year inside the dt
var o2 = new { Name, dt.Year }; 

While a few paragraphs back the author presented the following syntax for creating an anonymous type (2):

// Define a type, construct an instance of it, & initialize its properties
var o1 = new { Name = "Jeff", Year = 1964 }; 

So, from the above two excerpts I draw a conclusion that there is one syntax for declaring a property inside an anonymous type and two additional syntaxes for this. And while one of the additional syntaxes was presented in the book, I still do not see the second additional syntax being presented in the book.

I heard about the syntax and about the first additional syntax and I used them in a few occasions in my applications. But I can not remember using any other syntax (which would be the third).

All that makes me believe that there are actually only two syntaxes and the third (which is second additional) does not exist. And the excerpt presented above is just a mistake in the book: the author should have written

... supports two additional ...

Also, I was not able to find anything on the third syntax on the internet.

So, is it just a mistake or am I missing the third syntax here?


Solution

  • From the documentation:

    You create anonymous types by using the new operator together with an object initializer.

    The object initializer syntax is described here. It's this syntax:

    { PropertyName = value, ... }
    

    And back on the anonymous type documentation:

    If you do not specify member names in the anonymous type, the compiler gives the anonymous type members the same name as the property being used to initialize them.

    So, there is only one syntax:

    new {[PropertyName =] value, ...}
    

    The PropertyName = part is optional if the value is a property. (What about fields?).

    Like it was said in the comments, your source is poorly worded.