C# Anonymous Types

h‮//:sptt‬www.theitroad.com

In C#, anonymous types are a feature that allows you to create a type on the fly without defining it explicitly in your code. Anonymous types are often used for temporary data storage or to pass data to a method or a function.

To create an anonymous type, you use the new keyword and an object initializer syntax to define the properties of the anonymous type. The properties of the anonymous type are inferred from the values assigned to them. Here's an example:

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

In this example, we create an anonymous type with two properties Name and Age. The property names are inferred from the property names used in the object initializer syntax, and the property types are inferred from the types of the values assigned to them.

You can also use anonymous types in LINQ queries to create temporary objects for the results. For example:

var people = new[] {
    new { Name = "John", Age = 30 },
    new { Name = "Jane", Age = 25 },
    new { Name = "Bob", Age = 35 }
};

var result = from p in people
             where p.Age > 30
             select new { p.Name, p.Age };

In this example, we create an array of anonymous types representing people and then use LINQ to select people whose age is greater than 30. We then create another anonymous type with only the Name and Age properties and assign it to the result variable.

Anonymous types are read-only, which means that you cannot change their properties once they are created. They are also implicitly typed, which means that the type of an anonymous type is determined by the compiler at compile-time.