ZetCode

C# anonymous types

last modified November 15, 2026

This article shows how to work with anonymous types in C#. We cover creating them, inferred property names, equality, non-destructive mutation, LINQ projections, JSON serialization, and their limitations.

An anonymous type is a class without a name that the compiler generates from an object creation expression such as new { Name = "Lucy", Age = 28 }. The compiler infers the property names and types from the initializer. Because the type has no name we can write, variables holding anonymous objects are declared with var.

Anonymous types are reference types derived directly from object. Their properties are read-only, and the compiler overrides Equals, GetHashCode, and ToString to work with the property values. Anonymous types are handy for grouping a few values locally, most often in LINQ queries, where they hold the results of projections and serve as composite keys.

Creating an anonymous type

An anonymous object is created with the new keyword followed by an object initializer, without a type name.

Program.cs
var user = new { Name = "John Doe", Age = 34, Active = true };

Console.WriteLine(user.Name);
Console.WriteLine(user.Age);
Console.WriteLine(user);

Type t = user.GetType();
Console.WriteLine(t.Name);

foreach (var prop in t.GetProperties())
{
    Console.WriteLine($"{prop.Name}: {prop.PropertyType.Name}, writable: {prop.CanWrite}");
}

We create an anonymous object and inspect its type with reflection.

var user = new { Name = "John Doe", Age = 34, Active = true };

The object has three properties of type string, int, and bool. The variable must be declared with var.

Console.WriteLine(user);

The generated ToString method prints the property names and values in curly brackets.

Type t = user.GetType();
Console.WriteLine(t.Name);

The compiler gives the type a name that is not valid in C#, so it cannot clash with our types. The `3 suffix shows that the type is generic with three type parameters, one for each property. The properties have only getters.

$ dotnet run
John Doe
34
{ Name = John Doe, Age = 34, Active = True }
<>f__AnonymousType0`3
Name: String, writable: False
Age: Int32, writable: False
Active: Boolean, writable: False

Inferred property names

If a member of the initializer is a variable, a field, or a property access, we can omit the property name. This is called a projection initializer; the property takes the name of the member.

Program.cs
string city = "Bratislava";
int population = 475503;
var now = new DateOnly(2026, 11, 15);

var info = new { city, population, now.Year, Upper = city.ToUpper() };
Console.WriteLine(info);

var uri = new Uri("https://zetcode.com/csharp/linq/?page=2");
var parts = new { uri.Scheme, uri.Host, uri.AbsolutePath, uri.Query };
Console.WriteLine(parts);

We build anonymous objects from local variables and from properties of other objects.

var info = new { city, population, now.Year, Upper = city.ToUpper() };

The city and population properties get their names from the variables, and the Year property from now.Year. A method call such as city.ToUpper() has no name to infer, so we must name the property explicitly.

var parts = new { uri.Scheme, uri.Host, uri.AbsolutePath, uri.Query };

Projection initializers make it easy to pick a few properties of a larger object.

$ dotnet run
{ city = Bratislava, population = 475503, Year = 2026, Upper = BRATISLAVA }
{ Scheme = https, Host = zetcode.com, AbsolutePath = /csharp/linq/, Query = ?page=2 }

Equality

The Equals method of an anonymous type compares the values of all properties. Two anonymous object creation expressions in the same assembly with the same property names, types, and order share the same generated type.

Program.cs
var a = new { Name = "Lucy", Age = 28 };
var b = new { Name = "Lucy", Age = 28 };
var c = new { Age = 28, Name = "Lucy" };

Console.WriteLine(a.Equals(b));
Console.WriteLine(a == b);
Console.WriteLine(a.GetHashCode() == b.GetHashCode());

Console.WriteLine(a.GetType() == b.GetType());
Console.WriteLine(a.GetType() == c.GetType());

var people = new HashSet<object> { a, b, c };
Console.WriteLine(people.Count);

We compare three anonymous objects.

Console.WriteLine(a.Equals(b));
Console.WriteLine(a == b);

The objects a and b are equal according to Equals. The == operator is not overloaded for anonymous types; it compares references and returns false. This differs from records, which overload ==.

Console.WriteLine(a.GetType() == c.GetType());

The object c has the same properties in a different order, so it is of a different type.

var people = new HashSet<object> { a, b, c };

Since Equals and GetHashCode are value-based, the set treats a and b as one element.

$ dotnet run
True
False
True
True
False
2

Non-destructive mutation

The properties of an anonymous object cannot be changed. Since C# 10, we can use a with expression to create a copy with some properties changed.

Program.cs
var product = new { Name = "Pencil", Price = 1.5m, Stock = 120 };
var discounted = product with { Price = 1.2m };
var sold = discounted with { Stock = discounted.Stock - 20 };

Console.WriteLine(product);
Console.WriteLine(discounted);
Console.WriteLine(sold);

We make modified copies of a product.

var discounted = product with { Price = 1.2m };
var sold = discounted with { Stock = discounted.Stock - 20 };

Each with expression returns a new object of the same anonymous type. The original product stays unchanged.

$ dotnet run
{ Name = Pencil, Price = 1.5, Stock = 120 }
{ Name = Pencil, Price = 1.2, Stock = 120 }
{ Name = Pencil, Price = 1.2, Stock = 100 }

Anonymous types in LINQ

LINQ is the main use case for anonymous types. They hold projected data in Select and composite keys in GroupBy, Join, and OrderBy.

Program.cs
var cars = new[]
{
    new { Name = "Audi", Brand = "VW", Price = 52642, Year = 2023 },
    new { Name = "Skoda", Brand = "VW", Price = 22000, Year = 2024 },
    new { Name = "Mercedes", Brand = "Daimler", Price = 57127, Year = 2023 },
    new { Name = "Smart", Brand = "Daimler", Price = 18900, Year = 2024 },
    new { Name = "Volvo", Brand = "Geely", Price = 29000, Year = 2024 },
};

Console.WriteLine(cars.GetType().Name);

var cheap = cars
    .Where(car => car.Price < 30000)
    .Select(car => new { car.Name, PriceK = car.Price / 1000.0 });

foreach (var car in cheap)
{
    Console.WriteLine($"{car.Name}: {car.PriceK:F1}k");
}

var groups = cars
    .GroupBy(car => new { car.Brand, car.Year })
    .OrderBy(g => g.Key.Brand)
    .ThenBy(g => g.Key.Year);

foreach (var g in groups)
{
    Console.WriteLine($"{g.Key.Brand} {g.Key.Year}: {string.Join(", ", g.Select(car => car.Name))}");
}

We filter, project, and group an array of cars.

var cars = new[]
{
new { Name = "Audi", Brand = "VW", Price = 52642, Year = 2023 },

An implicitly typed array new[] can hold anonymous objects, provided they all have the same type. Collection expressions cannot be used here because they need a target type that we can name.

.Select(car => new { car.Name, PriceK = car.Price / 1000.0 });

The projection creates new anonymous objects with only the data we need.

.GroupBy(car => new { car.Brand, car.Year })

The cars are grouped by two properties at once. Grouping relies on the value-based Equals and GetHashCode, so cars with the same brand and year end up in the same group. The key's properties are accessible through g.Key.

$ dotnet run
<>f__AnonymousType0`4[]
Skoda: 22.0k
Smart: 18.9k
Volvo: 29.0k
Daimler 2023: Mercedes
Daimler 2024: Smart
Geely 2024: Volvo
VW 2023: Audi
VW 2024: Skoda

JSON serialization

Anonymous objects are a quick way to produce JSON without declaring classes. The serializer reads their public properties like those of any other object.

Program.cs
using System.Text.Json;

var order = new
{
    Id = 1042,
    Customer = new { Name = "Paul", Email = "paul@example.com" },
    Items = new[]
    {
        new { Sku = "A-11", Qty = 2 },
        new { Sku = "B-07", Qty = 1 },
    }
};

string json = JsonSerializer.Serialize(order, new JsonSerializerOptions { WriteIndented = true });
Console.WriteLine(json);

var template = new { Id = 0, Customer = new { Name = "", Email = "" } };
var parsed = DeserializeAs(template, """{"Id": 7, "Customer": {"Name": "Anna", "Email": "anna@example.com"}}""");
Console.WriteLine(parsed.Customer.Name);

static T DeserializeAs<T>(T template, string json) => JsonSerializer.Deserialize<T>(json)!;

We serialize a nested anonymous object and deserialize JSON back into an anonymous type.

string json = JsonSerializer.Serialize(order, new JsonSerializerOptions { WriteIndented = true });

Nested anonymous objects become nested JSON objects, and arrays become JSON arrays.

var template = new { Id = 0, Customer = new { Name = "", Email = "" } };

To deserialize into an anonymous type, we need to tell the serializer the type, but we cannot write its name. The generic DeserializeAs method lets the compiler infer T from a template object whose values are ignored. The serializer fills the read-only properties through the constructor of the anonymous type.

$ dotnet run
{
  "Id": 1042,
  "Customer": {
    "Name": "Paul",
    "Email": "paul@example.com"
  },
  "Items": [
    {
      "Sku": "A-11",
      "Qty": 2
    },
    {
      "Sku": "B-07",
      "Qty": 1
    }
  ]
}
Anna

Limitations

An anonymous type can only be named by the compiler, which limits where it can be used. A method cannot declare it as a return type or a parameter type, and a class cannot have a field of an anonymous type.

Program.cs
object obj = GetUser();
Console.WriteLine(obj);

var tuple = GetUserTuple();
Console.WriteLine($"{tuple.Name} is {tuple.Age}");

var rec = GetUserRecord();
Console.WriteLine($"{rec.Name} is {rec.Age}");

static object GetUser() => new { Name = "Roger", Age = 41 };

static (string Name, int Age) GetUserTuple() => ("Roger", 41);

static User GetUserRecord() => new("Roger", 41);

record User(string Name, int Age);

We return the same data from methods in three ways.

static object GetUser() => new { Name = "Roger", Age = 41 };

An anonymous object can be returned as object, but the caller then loses access to its properties. It can only print it or use reflection or dynamic.

static (string Name, int Age) GetUserTuple() => ("Roger", 41);
static User GetUserRecord() => new("Roger", 41);

When data leaves a method, a named tuple or a record is the better choice. Tuples are lightweight value types; records give us a real named type with value equality.

$ dotnet run
{ Name = Roger, Age = 41 }
Roger is 41
Roger is 41

Compile-time errors

The compiler enforces the read-only properties and hides the members when the static type is object.

Program.cs
var point = new { X = 1, Y = 2 };
point.X = 5;

object obj = point;
Console.WriteLine(obj.X);

The program tries to change a property and to read a property through an object variable.

point.X = 5;

Assigning to a property of an anonymous type is an error; use a with expression instead.

Console.WriteLine(obj.X);

After the assignment to object, the compiler no longer knows about the X property. The program does not compile.

$ dotnet build
Program.cs(2,1): error CS0200: Property or indexer '<anonymous type: int X, int Y>.X' cannot be assigned to -- it is read only
Program.cs(5,23): error CS1061: 'object' does not contain a definition for 'X' and no accessible extension method 'X' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

Source

Anonymous types

Choose between anonymous and tuple types

In this article we have worked with anonymous types in C#. See also the tuple, record, LINQ Select, and LINQ group by tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.