Search⌘ K
AI Features

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.

C# 14.0
// We create an anonymous type using the 'new' keyword
// followed by an object initializer.
var person = new { Name = "John", Age = 27 };
Console.WriteLine($"Type: {person.GetType()}");
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
// Anonymous types override ToString() to display their contents
Console.WriteLine($"ToString: {person}");
  • Line 3: We create a new object with Name and Age properties. We assign it to a variable declared with var because the type name is unknown to us.

  • Line 5: We print the type name. The compiler generates a name like <>f__AnonymousType0... ...