Anonymous Types
An anonymous type is a simple class created on the fly to
store a set of values. To create an anonymous type, you use the new keyword followed by an object initializer,
specifying the properties and values the type will contain. For
example:
var dude = new { Name = "Bob", Age = 1 };The compiler resolves this by writing a private nested type with
read-only properties for Name (type
string) and Age (type int). You must use the var keyword to reference an anonymous type,
because the type’s name is compiler-generated.
The property name of an anonymous type can be inferred from an expression that is itself an identifier. For example:
intAge= 1; var dude = new { Name = "Bob",Age};
is equivalent to:
var dude = new { Name = "Bob", Age = Age };You can create arrays of anonymous types as follows:
var dudes = new[]
{
new { Name = "Bob", Age = 30 },
new { Name = "Mary", Age = 40 }
};Anonymous types are used primarily when writing LINQ queries.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access