C# Language Anonymous types


Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first. The type name is generated by the compiler and is not available at the source code level. The type of each property is inferred by the compiler.

You can make anonymous types by using the new keyword followed by a curly brace ({). Inside the curly braces, you could define properties like on code below.

var v = new { Amount = 108, Message = "Hello" };

It's also possible to create an array of anonymous types. See code below:

var a = new[] { 
    new { 
        Fruit = "Apple", 
        Color = "Red" 
    new {
        Fruit = "Banana",
        Color = "Yellow"

Or use it with LINQ queries:

var productQuery = from prod in products
                   select new { prod.Color, prod.Price };