Anonymous Types

You can define anonymous types which is a great way to define temporary types used for data storage types. Suppose that you just want a class that can hold three values inside its properties.

public class Sample
{
    public int Property1 { get; set; }
    public double Property2 { get; set; }
    public string Property3 { get; set; }
}

With anonymous types, you don’t need to create storage classes such as the one shown above. You can define an anonymous type that has the same properties as the one above.

var anonymousType = new 
    { Property1 = 10, 
      Property2 = 5.35,
      Property3 = "Hello" };

The var keyword was used. The syntax is the same as object initializers but we didn’t indicate a name of the class. After that declaration, you can use the properties of the anonymous type.

Console.WriteLine(anonymousType.Property1);
Console.WriteLine(anonymousType.Property2);
Console.WriteLine(anonymousType.Property3);

Note that once initialized, you cannot modify the values of the property of an anonymous type because they are readonly properties.