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 and Age 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

LimitationExplanation
Read-only propertiesCannot modify after creation
Cannot be used as method return type (unless var or dynamic)Type is compiler-generated
Cannot inherit from other classesThey are sealed by default
Only useful locallyNot ideal for public API return values

πŸ“Œ 6. Advantages

  1. Quick and lightweight objects

  2. Great for temporary data storage

  3. Perfect for LINQ projections

  4. 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

FeatureDescription
Syntaxvar obj = new { Prop1 = val1, Prop2 = val2 };
PropertiesRead-only, compiler-inferred types
Common Use CaseTemporary objects, LINQ projections
LimitationsCannot modify, cannot inherit, limited scope
AdvantageQuick, 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.