Anonymous types in C# are a feature that allows us to create objects at runtime without having to explicitly define a class.
They provide a quick and convenient way to encapsulate a set of properties into a single object without needing to define a specific class for it.
These types were introduced in C# 3.0 and are commonly used in scenarios where temporary data storage is needed (for example, in LINQ queries).
Some characteristics of anonymous types are,
- Immutability: Once created, an anonymous type cannot change its properties.
- Strongly Typed: Although anonymous, these types are strongly typed and their structure is known at compile time.
- Temporary Use: They are ideal for storing temporary data, especially in LINQ queries.
Creating Anonymous Types
To create an anonymous type, you use the new keyword followed by an object initializer. Here’s a simple example:
var person = new { Name = "Luis", Age = 30 };
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
In this example, person is an anonymous type with two properties: Name and Age.
Anonymous types have certain limitations. For example, you cannot define methods in them, and they cannot be used outside the scope in which they were created.
Using Anonymous Types
Anonymous Types with Lambda Expressions
Anonymous types are frequently used with lambda expressions, especially in the context of LINQ.
var people = new[]
{
new { Name = "Lucía", Age = 25 },
new { Name = "Marta", Age = 28 }
};
var names = people.Select(p => new { p.Name });
foreach (var name in names)
{
Console.WriteLine(name.Name);
}
Anonymous Types with Methods
Anonymous types can be returned from methods, but care must be taken as the return type cannot be explicitly specified. In these cases, var is usually used.
var result = CreateAnonymousType();
Console.WriteLine($"Name: {result.Name}, Age: {result.Age}");
var CreateAnonymousType()
{
return new { Name = "Carlos", Age = 28 };
}
Nested Anonymous Types
It is possible to create nested anonymous types, meaning one anonymous type inside another.
var company = new
{
Name = "TechCorp",
Employee = new { Name = "Ana", Age = 29 }
};
Console.WriteLine($"Company: {company.Name}, Employee: {company.Employee.Name}, Age: {company.Employee.Age}");
