C# Feature – Anonymous types
Overview
Section titled “Overview”Anonymous types create object instances without declaring a formal class, often used in LINQ projections.
Introduced In
Section titled “Introduced In”C# 3 (2007)
Before
Section titled “Before”class PersonView { public string Name { get; set; } public int Age { get; set; } }
var person = new { Name = "Ada", Age = 42 };
Annotated Example
Section titled “Annotated Example”var query = people.Select(p => new { p.Name, IsAdult = p.Age >= 18 });
Gotchas & Best Practices
Section titled “Gotchas & Best Practices”- Scope-limited; types are compiler-generated and local to the assembly.
- Great for projections; avoid returning anonymously typed values from public APIs.
Related Features
Section titled “Related Features”Version Notes
Section titled “Version Notes”- Works seamlessly with
var
type inference.