C# Anonymous Types


Often you need to create simple boring classes for data representation, especially in database applications. You end up with a bunch of classes that don’t do anything. They don’t have any methods, they only have properties. These classes are used to store structured data. You might think of this as a row in a table.

A collection class that was capable of holding instances of this class would be a representation of multiple rows in a table or a spreadsheet. This is a perfectly good use of classes. It is used extensively in ASP.NET applications. You can simplify this coding style with anonymous types.

An anonymous type is used when you want to allow the C# compiler to create types based on the data you want to store in them. Anonymous types are often used for the results of LINQ queries.

public class Person
{
   public string FirstName {get; set; }
   public string LastName { get; set; }
}
// instantiate
var person = new Person
{
   FirstName = "Bob",
   LastName = "Smith"
}

Here is the way to do it with an anonymous type. First, you use the var keyword. You must use the var keyword. Secondly there is no identifier after the new keyword. That is how the compiler knows you want to use an anonymous type. Internally there is an identifier but you as the programmer don’t have access to it. Note that the properties are internally defined as read-only properties. If you need to change the values, you cannot use anonymous types. You cannot assign to the properties of an object of an anonymous type. The properties created by the compiler for an anonymous type are read-only properties.

var person = new
{
   FirstName = "Bob",
   LastName = "Smith"
}

The following code shows an example of creating and using an anonymous type. It creates a variable called student, with an anonymous type that has two string properties and one int property. Notice in the WriteLine statement that the instance’s members are accessed just as if they were members of a named type.

namespace AnonymousTypes
{
    class Program
    {
        static void Main(string[] args)
        {
            var student = new { Name = "Mary Jones", Age = 19, Major = "History" };
            Console.WriteLine($"{ student.Name }, Age { student.Age }, Major: {student.Major}");
        }
    }
}

In the above example, Name = “Mary Jones” is a member initializer. The anonymous object initializer is {Name = “Mary Jones”, Age = 19, Major = “History”}. When the compiler encounters the object initializer of an anonymous type, it creates a new class type with a private name that it constructs. For each member initializer, it infers its type and creates a read-only property to access its value. The property has the same name as the member initializer. Once the anonymous type is constructed, the compiler creates an object of that type.

using System;
namespace AnonymousTypes
{
    class Program
    {
        static void Main(string[] args)
        {
            var student = new { Name = "Mary Jones", Age = 19, Major = "History" };
            Console.WriteLine($"{ student.Name }, Age { student.Age }, Major: {student.Major}");
            // the code below produces the same results
            // page 511 of book Illustrated C# 7
            string Major = "History";
            var person = new { Age = 19, Other.Name, Major };
            Console.WriteLine($"{person.Name }, Age {person.Age }, Major: {person.Major}");
            // Mary Jones, Age 19, Major: History
        }
    }
    class Other
    {
        // Name is a static field of class Other
        static public string Name = "Mary Jones";
    }
}