Anonymous types in C# are generic because the compiler needs a distinct, statically typed shape for each set of properties, and generics are the only mechanism that lets the runtime create a unique type per shape without generating a new named class for every combination. In other words, the generic type parameter encodes the property names and types, so two anonymous objects with the same property names and types share a type, while different shapes get different types.
Background: What Anonymous Types Are
Anonymous types are a C# feature introduced in version 3.0 alongside LINQ. They let you create an object without explicitly declaring a class, using syntax like new { Name = "Ada", Age = 36 }. The compiler generates a class behind the scenes, but you never see its name in source code. This is useful for projections in LINQ queries, where you want to return a subset of properties without defining a dedicated type.
The generated class is always a reference type, immutable (all properties are get-only), and overrides Equals, GetHashCode, and ToString based on the properties. But the key design question is: how does the compiler give each anonymous type a unique identity? The answer lies in generics.
How Generics Provide Unique Type Identity
When you write new { Name = "Ada", Age = 36 }, the compiler creates a generic class <>f__AnonymousType0<T1, T2> and instantiates it with the types of the properties. The generic type parameters are not the property names themselves; rather, the compiler generates a distinct generic type definition for each combination of property names and their order. For example, new { Name = "Ada", Age = 36 } might use <>f__AnonymousType0<string, int>, while new { Age = 36, Name = "Ada" } uses a different generic type definition because the property order differs. The type arguments are the property types, and the generic type definition is unique to the property names and their order.
This approach allows the runtime to treat two anonymous objects with the same property names, types, and order as the same type, enabling equality comparisons and type checking. If anonymous types were not generic, the compiler would have to emit a new non-generic class for every distinct set of properties, which would bloat assemblies and complicate type identity.
Why Not Just Generate a New Class for Each Shape?
Generics offer several advantages over generating a separate non-generic class for each anonymous type shape:
- Code reuse: A single generic type definition can be instantiated with different property types, reducing the number of generated types. For instance,
new { Id = 1 }andnew { Id = 2L }share the same generic type definition but differ in type arguments. - Type identity: Two anonymous objects with the same property names, types, and order are considered the same type by the compiler, which is essential for equality and assignment. Generics make this identity explicit through type arguments.
- Performance: Generic types are instantiated once per set of type arguments, so the runtime can avoid creating redundant types. This is particularly important in LINQ queries where anonymous types are used heavily.
Without generics, the compiler would need to generate a new class for every anonymous type expression, even if the shapes were identical, leading to type explosion and preventing equality comparisons across different expressions.
How the Compiler Generates Anonymous Types
The C# compiler follows a specific process when it encounters an anonymous type:
- It collects the property names and their inferred types from the initializer.
- It checks if an anonymous type with the same property names, types, and order already exists in the assembly. If so, it reuses that type.
- If not, it generates a new generic type definition with a name like
<>f__AnonymousType0<T1, T2>, where the number and type parameters correspond to the properties. - It emits a constructor that takes the property values and assigns them to read-only properties.
- It overrides
Equals,GetHashCode, andToStringto use the properties.
The generic type parameters are the types of the properties, and the generic type definition is unique to the property names and their order. This means that new { A = 1, B = "x" } and new { A = 2, B = "y" } share the same type, but new { B = "x", A = 1 } has a different type because the order of properties differs.
Common Misconceptions and Related Questions
Misconception: Anonymous types are generic because they can hold any type. Reality: They are generic because the compiler uses generics to parameterize the property types, but the generic type definition itself is fixed for a given set of property names and order. The genericity is about type parameters, not about flexibility in property names.
Misconception: You can use anonymous types as generic type arguments. Reality: You cannot explicitly use an anonymous type as a type argument because it has no name. However, you can use type inference (e.g., var) to store them, and they can be used in generic methods via inference.
Related question: Why can't anonymous types be used as return types? Because they have no name, you cannot declare a method return type as an anonymous type. You must use object, dynamic, or a named type.
Frequently Asked Questions
Why are anonymous types immutable?
Anonymous types are immutable (properties are read-only) to ensure that the hash code and equality semantics remain consistent. If properties could change, using them as keys in dictionaries or in LINQ operations would be unreliable.
Can two anonymous types with the same property names but different order be equal?
No, the order of properties matters. The compiler generates different generic type definitions for different property orders, so they are not the same type and cannot be compared for equality.
Are anonymous types value types or reference types?
Anonymous types are reference types (classes), even though they behave like value types in terms of equality. They are allocated on the heap.
Why does the compiler generate generic types with weird names like <>f__AnonymousType0?
The names are deliberately unspeakable (containing angle brackets) to prevent you from using them directly in code. This avoids naming collisions and ensures that anonymous types remain anonymous.
Can I use anonymous types in method signatures?
No, because they have no name. You can use them locally with var, but you cannot declare a parameter or return type as an anonymous type. You can use object or dynamic instead, but you lose static typing.
Do anonymous types affect performance?
Anonymous types are compiled to regular generic classes, so their performance is similar to named classes. The generic instantiation is cached by the runtime, so there is no significant overhead.
Alternatives to Anonymous Types
While anonymous types are convenient for short-lived projections, they have limitations: they cannot be used as method return types, and they are not serializable by default. Alternatives include:
- Tuples: C# 7.0 introduced value tuples, which are mutable and can be used as return types, but they lack property names (though they can be named).
- Records: C# 9.0 introduced records, which are named types with value-based equality and immutability, suitable for data transfer objects.
- Named classes: For more complex scenarios, defining a class gives you full control over serialization, methods, and interfaces.
Anonymous types remain the best choice for LINQ projections where you need a quick, immutable shape without defining a type.
Summary
Anonymous types are generic because generics provide a way to create a unique type per property shape while reusing a single generic type definition. This design enables type identity, equality, and performance benefits. The generic type parameters are the property types, and the generic type definition is unique to the property names and order. Understanding this helps developers appreciate the compiler's role and the limitations of anonymous types.