Creating an anonymous type

suggest change

Since anonymous types are not named, variables of those types must be implicitly typed (var).

var anon = new { Foo = 1, Bar = 2 };
// anon.Foo == 1
// anon.Bar == 2

If the member names are not specified, they are set to the name of the property/variable used to initialize the object.

int foo = 1;
int bar = 2;
var anon2 = new { foo, bar };
// anon2.foo == 1
// anon2.bar == 2

Note that names can only be omitted when the expression in the anonymous type declaration is a simple property access; for method calls or more complex expressions, a property name must be specified.

string foo = "some string";
var anon3 = new { foo.Length };
// anon3.Length == 11
var anon4 = new { foo.Length <= 10 ? "short string" : "long string" };
// compiler error - Invalid anonymous type member declarator.
var anon5 = new { Description = foo.Length <= 10 ? "short string" : "long string" };
// OK

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Anonymous types:
* Creating an anonymous type

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
33 Anonymous types
36 Casting
46 Methods
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script