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 in a single object without having 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, such as in LINQ queries.
Some of the features of anonymous types are:
- Immutability: Once created, an anonymous type cannot change its properties.
- Strong typing: Although they are anonymous, anonymous 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, the new
keyword is used followed by an object initializer. Here is a simple example:
var person = new { Name = "Juan", 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, methods cannot be defined on them nor can they 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, that is, an anonymous type within another anonymous type.
var company = new
{
Name = "TechCorp",
Employee = new { Name = "Ana", Age = 29 }
};
Console.WriteLine($"Company: {company.Name}, Employee: {company.Employee.Name}, Age: {company.Employee.Age}");