Letβs go through anonymous types in C# β a handy way to create lightweight objects without defining a class.
π 1. What Are Anonymous Types?
-
Anonymous types are objects created on the fly without explicitly declaring a class.
-
Useful when you need a temporary object to hold some data.
-
Properties are read-only.
-
Type is inferred by the compiler.
π 2. Syntax
var obj = new { Property1 = value1, Property2 = value2 };
-
Use
var
(type inference) -
Property names and values are defined inline
π 3. Example
var person = new { Name = "Alice", Age = 25 };
Console.WriteLine(person.Name); // Alice
Console.WriteLine(person.Age); // 25
-
No class
Person
needed -
Properties
Name
andAge
are read-only
π 4. Using Anonymous Types in LINQ
Anonymous types are commonly used in LINQ for projection:
var students = new[]
{
new { Name = "Alice", Age = 20 },
new { Name = "Bob", Age = 22 }
};
// Select only names
var names = from s in students
select new { s.Name };
foreach (var n in names)
Console.WriteLine(n.Name); // Alice, Bob
- Avoids creating a separate class just to hold the projected data
π 5. Limitations of Anonymous Types
Limitation | Explanation |
---|---|
Read-only properties | Cannot modify after creation |
Cannot be used as method return type (unless var or dynamic ) | Type is compiler-generated |
Cannot inherit from other classes | They are sealed by default |
Only useful locally | Not ideal for public API return values |
π 6. Advantages
-
Quick and lightweight objects
-
Great for temporary data storage
-
Perfect for LINQ projections
-
No need to clutter code with small class definitions
π 7. Example: Multiple Properties in LINQ
var students = new[]
{
new { Name = "Alice", Age = 20 },
new { Name = "Bob", Age = 22 }
};
var result = students.Select(s => new { s.Name, IsAdult = s.Age >= 21 });
foreach (var r in result)
Console.WriteLine($"{r.Name} - Adult: {r.IsAdult}");
Output:
Alice - Adult: False
Bob - Adult: True
- Added computed property
IsAdult
in the anonymous type
π 8. Summary Table
Feature | Description |
---|---|
Syntax | var obj = new { Prop1 = val1, Prop2 = val2 }; |
Properties | Read-only, compiler-inferred types |
Common Use Case | Temporary objects, LINQ projections |
Limitations | Cannot modify, cannot inherit, limited scope |
Advantage | Quick, concise, no extra class needed |
β Tip:
-
Use anonymous types when you need a quick object for short-term use, especially inside LINQ queries.
-
For long-term or reusable objects, define a named class instead.