Anonymous types are types that are generated by compiler at run time. When we create a anonymous type we do not specify a name. We just write properties names and their values. Compiler at runtime create these properties and assign values to them.
var k = new { FirstProperty = "value1", SecondProperty = "value2" };
Console.WriteLine(k.FirstProperty);
Anonymous class is useful in LINQ queries to save our intermediate results.
There are some restrictions on Anonymous types as well:
- Anonymous types can not implement interfaces.
- Anonymous types can not specify any methods.
- We can not define static members.
- All defined properties must be initialized.
- We can only define public fields.