Anonymous Types in C#
What are Anonymous Types in C#?
Anonymous types in C# allow you to create objects without explicitly defining a class. They are useful for scenarios where you need a temporary object with read-only properties.
Key Features of Anonymous Types
- Used to create objects without defining an explicit class.
- Properties are read-only (immutable).
- Uses the
var
keyword for type inference. - Commonly used with LINQ queries for projection.
Example of Anonymous Type
The following example demonstrates how to create and use an anonymous type.
Example: Creating an Anonymous Type
using System;
class Program
{
static void Main()
{
var person = new { Name = "John", Age = 30 };
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
}
// Output:
// Name: John, Age: 30
Here, the person
object has properties Name
and Age
, but no explicit class is defined.
Using Anonymous Types in LINQ
Anonymous types are widely used in LINQ queries to project only required properties.
Example: LINQ with Anonymous Types
using System;
using System.Linq;
class Program
{
static void Main()
{
var students = new[]
{
new { Name = "Alice", Score = 85 },
new { Name = "Bob", Score = 92 },
new { Name = "Charlie", Score = 78 }
};
var topStudents = from s in students
where s.Score > 80
select new { s.Name, s.Score };
foreach (var student in topStudents)
{
Console.WriteLine($"Name: {student.Name}, Score: {student.Score}");
}
}
}
// Output:
// Name: Alice, Score: 85
// Name: Bob, Score: 92
In this example, LINQ filters students with scores above 80 and projects only Name
and Score
using an anonymous type.
Limitations of Anonymous Types
- Anonymous types are immutable (cannot modify properties).
- They are only accessible within the same method or scope.
- Cannot define methods inside anonymous types.
- Cannot be explicitly declared (must use
var
keyword).
When to Use Anonymous Types?
- When you need a temporary object with read-only properties.
- For grouping or projecting specific properties in LINQ queries.
- When defining a separate class would be unnecessary.
Anonymous Types vs. Tuples
Both anonymous types and tuples allow temporary object creation, but they have differences.
Feature | Anonymous Types | Tuples |
---|---|---|
Mutability | Immutable (read-only) | Mutable (modifiable properties) |
Field Names | Has named properties | Uses default names (Item1, Item2, etc.) unless defined |
Scope | Limited to the method where declared | Can be passed between methods |
Best Use Case | For LINQ projections and short-lived objects | For returning multiple values from a method |