User Tools

Site Tools


notes:csharp:anonymoustypes

Anonymous Types in C#

An anonymous type is a class created by the compiler. Its definition is inferred from the initializer and its properties are read-only. Consider using an anonymous type for a type that is used in a single method and that contains only trivial properties.

Within an assembly, two anonymous objects are of the same type if:

  • they have the same number of properties
  • their properties have the same names and types
  • they appear in the same order
// An object of an anonymous type.
var book1 = new { Title = "AAA", Author = "Author1", Price = 10.99M };
 
// Another object of the same type as book1.
var book2 = new { Title = "BBB", Author = "Author2", Price = 11.99M };

You can also create an array of anonymously typed elements:

var books = new[]
{
    new { Title = "AAA", Author = "Author1", Price = 10.99M },
    new { Title = "BBB", Author = "Author2", Price = 11.99M }
};

Anonymous types are commonly used with LINQ in the select clause of a query expression:

List<Book> books = new List<Book>();
books.Add(new Book { Title = "Title1", Author = "Author1", Price = 10M, IsKindle = false });
books.Add(new Book { Title = "Title2", Author = "Author2", Price = 20M, IsKindle = true });
books.Add(new Book { Title = "Title3", Author = "Author3", Price = 30M, IsKindle = false });
 
// kindleBooks is a collection of objects of an anonymous type { string Title, string Author }
var kindleBooks = from book in books
                  where book.IsKindle
                  // property names from 'book' are projected to an object of the anonymous type
                  select new { book.Title, book.Author };
 
// bookInfo is a collection of objects of an anonymous type { string Info }
var bookInfo = from book in books
               select new { Info = book.Title + ", " + book.Author };
...
class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
    public decimal Price { get; set; }
    public bool IsKindle { get; set; }
}

Links:

notes/csharp/anonymoustypes.txt · Last modified: 2016/10/13 by admin