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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s