CSharp - Type Creation Anonymous Types

Introduction

To create an anonymous type, use the new keyword followed by an object initializer.

In the object initializer, you can specify its properties and fields.

For example:

var dude = new { Name = "C#", Age = 23 };

You must use the var keyword to reference an anonymous type, because it doesn't have a name.

The property name of an anonymous type can be inferred from an expression. For example:

int Age = 23;
var dude = new { Name = "C#", Age, Age.ToString().Length };

is equivalent to:

var dude = new { Name = "C#", Age = Age, Length = Age.ToString().Length };

Two anonymous type instances declared within the same assembly will have the same underlying type if their elements are named and typed identically:

var a1 = new { X = 2, Y = 4 };
var a2 = new { X = 2, Y = 4 };
Console.WriteLine (a1.GetType() == a2.GetType());   // True

The Equals method is overridden to perform equality comparisons:

Console.WriteLine (a1 == a2);         // False
Console.WriteLine (a1.Equals (a2));   // True

You can create arrays of anonymous types as follows:

var vars = new[]
{
       new { Name = "C#", Age = 30 },
       new { Name = "Tom", Age = 40 }
};

To return an anonymously typed object, use object or dynamic:

dynamic Test() => new { Name = "C#", Age = 30 };  // No static type safety.