LINQ Interview Question #17
What is an anonymous type and how is it used with LINQ?
LINQ Fundamentals, Syntax, IEnumerable & IQueryable Junior Beginner
Quick Interview Answer
An anonymous type is a compiler-generated type created with the new { ... } syntax without explicitly declaring a class. It is useful for local projections where a temporary strongly typed shape is sufficient.
Detailed Explanation
An anonymous type is a compiler-generated type created with the new { ... } syntax without explicitly declaring a class. It is useful for local projections where a temporary strongly typed shape is sufficient.
Anonymous types are normally limited to the method or local context where their inferred type is available. Public application boundaries generally use named DTOs or view models instead.
Code Example
var result = products.Select(p => new
{
ProductName = p.Name,
FinalPrice = p.Price * 1.18m
});