When a C# LINQ query projects into new { l.Title, l.Author }, what type does the compiler create, and how do its instances compare?
answer
- a class you cannot name
- read-only, names inferred
- Equals looks at every property
- == still compares references
- why Distinct and group keys work
basics
~20 sThe compiler generates an internal sealed class with read-only properties named after the projected members. It overrides Equals, GetHashCode and ToString using the property values, so Distinct, group keys and join keys work, but == still compares references.
solid answer
~50 s`select new { l.Title, l.Author }` makes the compiler emit an **anonymous type**: an `internal sealed class` with read-only properties `Title` and `Author`, their names inferred from the member accesses. You cannot name it, so the query variable is declared with `var`. Every anonymous-object expression in the assembly with the same property names, types and order reuses one generated type. That type overrides `Equals` and `GetHashCode` to compare all property values, and `ToString` to print `{ Title = Beloved, Author = Morrison }`. That is why `Distinct()`, `group … by new { … }` and composite `join` keys behave by value, while a plain class without those overrides would compare references. `==` is not overloaded, so `a == b` is still reference comparison. Assigning a property is CS0200; a `with` expression (C# 10) makes a modified copy.
code
csharp · 21 linesusing System.Linq;
Loan[] loans = [new("Beloved", "Morrison", "ana"), new("Beloved", "Morrison", "ben"), new("Earthsea", "Le Guin", "cy")];
var a = new { Title = "Beloved", Author = "Morrison" };
var b = new { Title = "Beloved", Author = "Morrison" };
Console.WriteLine(a.Equals(b)); // True: compiler-generated value equality
Console.WriteLine(a == b); // False: == on a class compares references
Console.WriteLine(a.GetType() == b.GetType()); // True: same names, types and order share one type
Console.WriteLine(a); // { Title = Beloved, Author = Morrison }
var anonymousRows = (from l in loans select new { l.Title, l.Author }).Distinct().Count();
var classRows = (from l in loans select new Row { Title = l.Title, Author = l.Author }).Distinct().Count();
Console.WriteLine($"{anonymousRows} {classRows}"); // 2 3
class Row
{
public string Title { get; set; } = "";
public string Author { get; set; } = "";
}
record Loan(string Title, string Author, string Member);go deeper
Recall that select new { … } creates a compiler-named class with read-only properties, declared with var.
Explain value-based Equals and GetHashCode, the one-type-per-shape rule, and why == still compares references.
Catch the review bug where a projection into a plain class makes Distinct, grouping or a composite key silently compare references.
Set the rule for projection types: anonymous inside a method, records or tuples once data crosses a method or API boundary.
## What the compiler generates An **anonymous type** is created by `new { … }` with no type name, most often in a query's `select` clause: ```csharp var rows = from l in loans select new { l.Title, l.Author }; ``` The compiler generates a class for it with these characteristics: - it is an `internal sealed class` deriving from `object`, with a compiler-chosen name you cannot write in source; - every property is `public` and **read-only**; - each property name is either given (`Name = expr`) or **inferred** from a simple name or member access (`l.Title` gives `Title`); - it overrides `Equals`, `GetHashCode` and `ToString`. Because the type has no usable name, a variable holding one is declared with `var`, and the type cannot appear as a method's parameter type, return type or a field type. It stays local to the method that creates it; returning it means typing it as `object` or using a generic type parameter, at which point callers lose the property names. ## One type per shape Two anonymous-object expressions in the same assembly that have the **same property names, the same types and the same order** share one generated type, so `new { Title = "Beloved", Author = "Morrison" }` written in two places produces objects of the same type. Changing the order, `new { Author = …, Title = … }`, produces a different type, and instances of the two never compare equal. ## Value equality, reference == The generated `Equals(object)` returns true when the other object is the same anonymous type and every pair of property values is equal, and `GetHashCode` combines the property values' hash codes. The consequences for queries are direct: | Operation on projected rows | Anonymous type | Plain class without overrides | |---|---|---| | `Distinct()` | removes rows with equal values | keeps every instance | | `group … by new { … }` | one group per value combination | one group per instance | | composite `join` keys | match by value | never match across instances | | `a.Equals(b)` | compares values | compares references | | `a == b` | compares references | compares references | The last row is the trap: anonymous types do not overload `==`, so `==` on two anonymous objects compares references, like any class. The equality rules themselves, and how to write `Equals` and `GetHashCode` for a named type, belong to the lesson on equality and hashing. ## Read-only and copied with with Assigning to a property fails at compile time: for `var row = new { Title = "Beloved" };`, the line `row.Title = "Sula";` gives CS0200: "Property or indexer '<anonymous type: string Title>.Title' cannot be assigned to -- it is read only". Since C# 10 a `with` expression creates a modified copy, `row with { Title = "Sula" }`; the details of nondestructive mutation are covered with `with` expressions. Read-only properties also make a row a safer dictionary or group key: no property can be reassigned after the row is stored, so its hash code stays put as long as the property values themselves are immutable, as strings and numbers are. ## Choosing a projection type 1. **Anonymous type**: the default for a projection consumed inside the same method, for composite keys, and for queries whose lambdas must become expression trees, where anonymous types are allowed. 2. **A tuple** such as `select (l.Title, l.Author)`: a value type with value equality, `==` support and deconstruction; how tuples compare with anonymous types is a topic of its own. 3. **A record or named class**: when the projection leaves the method, crosses an API or needs behaviour. A plain class must override `Equals` and `GetHashCode` before `Distinct` or grouping treats equal rows as duplicates; a record gets value equality generated. Whichever type you choose, the query syntax is the same: the `select` clause holds any expression, and the compiler passes it to `Select` as the body of the projection lambda. Only the equality and naming rules above change. A frequent review finding is a projection into a small named class with settable properties, followed by `Distinct()` that silently removes nothing.
- Can a C# method return the anonymous objects its LINQ query projects?Not with their own type, because the type has no name you can write. The method can return them as `object` or `IEnumerable<object>`, or through a generic type parameter, but callers then cannot read `Title` without reflection or `dynamic`. When results leave the method, project into a record or tuple instead.
- Why does new { Title = "Beloved", Author = "Morrison" } not equal new { Author = "Morrison", Title = "Beloved" } in C#?Property order is part of the shape. The two expressions have the same names and types in a different order, so the compiler generates two distinct anonymous types, and the generated `Equals` returns false for an object of another type even when every value matches.
- Anonymous types are structs, so they are copied by value.
- == on two anonymous objects compares their property values.
- Every new { } expression creates its own separate type.
- Anonymous-type properties can be set after construction.
- Distinct removes duplicates from any projection, whatever its type.