Anonymous types provide a way to encapsulate a set of read-only properties into a single object without having to first explicitly define a type. The type name is generated by the compiler and is not available at the source code level. The type of the properties is inferred by the compiler.
The following code snippet illustrates that, an anonymous type being initialized with two properties named Code and Name.
C# var evals = new {code="100" ,Name = "Mark"} VB.NET Dim evals = New With {code="100" ,Name = "Mark"} |
Anonymous types are typically used in the select clause of a query expression to return a subset of the properties from each object in the source sequence. For more information about queries, see LINQ Query Expressions (C# Programming Guide).
C# var productQuery = from prod in products select new { prod.Color, prod.Price }; foreach (var v in productQuery) { Console.WriteLine("Color={0}, Price={1}", v.Color, v.Price); } |