Anonymous Types
Explore how to create and use anonymous types in C#. Understand their characteristics such as immutability, property initialization, and use cases like LINQ. Learn how the compiler generates these types and how to utilize features like non-destructive mutation and projection initializers for efficient coding.
C# allows us to encapsulate a set of read-only properties into a single object without explicitly defining a class. These are known as anonymous types.
An anonymous type is a temporary class generated by the compiler. Because the generated class has no name we can reference, we must use the var keyword to hold the instance. We define properties using object initializer syntax.
Creating and using anonymous types
Let’s look at how to create a simple anonymous object.
Line 3: We create a new object with
NameandAgeproperties. We assign it to a variable declared withvarbecause the type name is unknown to us.Line 5: We print the type name. The compiler generates a name like
<>f__AnonymousType0......