Anonymous Types
Often, you do not want to create a new class just for storing the result of a query. C# 3.0 provides anonymous types that allow us to declare both an anonymous class and an instance of that class using object initializers. For instance, we can initialize an anonymous customer address object:
new { Customer = customer, Address = address }This declares an anonymous class with two properties, Customer and Address, and initializes it with an instance of the Customer class and an instance of the Address class. The C# compiler can infer the property types with the types of assigned values, so here, the Customer property type is the Customer class, and the Address property type is the Address class. As a normal, named class, anonymous classes can have properties of any type.
Behind the scenes, the C# compiler generates a unique name for the new type. This name cannot be referenced in application code; therefore, it is considered nameless.
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