Cast By Example

Consider this Anonymous Type code snippet:



The Anonymous Type is compiled into an Int32[] Array and the first index of that array is the integer value 34.

Now if we were to add another integer value to our anonymous array, Intellisense will present us with this..

Notice how the Intellisense gives us the exact same options that are available to us if/when we were to create an explicit int[] array. Notice the snippet below shows an explicit int[] array and the Intellisense for that int[] array:

Now let’s create another Anonymous Array, but this time we will add a Person type to the initializer.

Notice the .Dump of the Anonymous Type is now an array of Person. In other words, the Anonymous Type is now Person[] type! How does it do that?

According to Mads Torgersen, this magic inference is called “Cast-By-Example”. [ref]

A bit of an free-bee golden nugget, we can convert our array (the Anonymous Type) to a Generic List by calling the .ToList() method like this:

Notice the Intellisense gives us options that correspond to the Intellisense for List types.

.NET Anonymous Types

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first.
[ref]

Here’s an example of how to implement an Anonymous Type

    1 class Program

    2 {

    3     static void Main()

    4     {

    5         var thing = new { ID = 123, Name = “Frank” };

    6         Console.WriteLine(“ID: {0}, Name: {1}”, thing.ID, thing.Name);

    7         Console.ReadLine();

    8     }

    9 }

Notice how line 5 looks like an Object Initializer without the specification of an existing type. Line 5 simply creates a new “something” – there is no specification of a type. Hence the term, Anonymous Type!