Anonymous Types


Anonymous Types

Anonymous types allow you to create objects without defining a class. They are useful for projecting data into new shapes without the need to explicitly define a class.

Characteristics

  • Implicitly Typed - The compiler infers the type.
  • Read-Only Properties - Properties are read-only.
  • Equality - Instances of anonymous types are compared based on their property values.

Example

Suppose you have a list of employees and you want to project a subset of their properties into a new type.

var employees = new List<Employee>
{
    new Employee { Name = "John", Age = 30, Department = "HR" },
    new Employee { Name = "Jane", Age = 25, Department = "IT" }
};

// Project into anonymous type
var result = employees
    .Select(e => new
    {
        e.Name,
        e.Age
    });
foreach (var item in result)
{
    Console.WriteLine($"Name: {item.Name}, Age: {item.Age}");
}

In this example, an anonymous type is created with Name and Age properties. The resulting result variable holds a collection of these anonymous types.


Prev Next