In C#, an anonymous object is an object created without a predefined class or type. It’s often used when you need a simple data structure for a short duration without explicitly defining a class. Anonymous objects are typically created using the new keyword and an object initializer.
var person = new { FirstName = "John", LastName = "Doe", Age = 30 };
Console.WriteLine($"Name: {person.FirstName} {person.LastName}, Age: {person.Age}");
// You can create a group of anonymous objects by using collection
// initializer syntax. Here's how you can do it with the given person object:
var peoples = new[]
{
new { FirstName = "John", LastName = "Doe", Age = 30 },
new { FirstName = "Alice", LastName = "Smith", Age = 25 },
new { FirstName = "Bob", LastName = "Johnson", Age = 35 }
};
foreach (var person in people)
{
Console.WriteLine($"Name: {person.FirstName} {person.LastName}, Age: {person.Age}");
}