anonymous types in C#

In C#, anonymous types allow you to create objects without explicitly defining a class or a structure. Anonymous types are useful when you want to create a temporary object to hold a set of properties or values without the need for a formal type declaration.

Here's an example to illustrate anonymous types in C#:


var person = new { Name = "John", Age = 30, City = "New York" };

Console.WriteLine("Name: " + person.Name);
Console.WriteLine("Age: " + person.Age);
Console.WriteLine("City: " + person.City);

In the example above, we create an anonymous type using the new keyword followed by curly braces. Inside the curly braces, we specify the properties and their values. In this case, the anonymous type has three properties: Name, Age, and City.

We can access the properties of the anonymous type using dot notation, just like we would with any other object. The Console.WriteLine statements demonstrate how we can access and display the values of the properties.

Anonymous types are read-only, meaning you cannot modify their properties once they are created. They are primarily used for temporary data structures or when you need to quickly create objects to hold a specific set of values. Anonymous types are commonly used in LINQ queries to project data into a specific shape or when working with dynamic data.

It's important to note that anonymous types are implicitly defined by the compiler, and their type names are generated based on the properties and their values. Therefore, you cannot explicitly declare variables of an anonymous type. Instead, you use the var keyword to let the compiler infer the type.