Linq To Objects: Anonymous Types and Methods

One of the core language features that C# relies on heavily when working with Linq is implicit typing. Implicit typing allows users to create anonymous types, which are simply types constructed at compile time based on the RHS expression specified by using the new keyword in conjunction with the object initializer syntax.

Implicit typing also works with predefined types, however it’s important to note the difference between the two syntactically similar statements, as they yield very different results:

var a = new int [] { 42 };

Create a new instance of a predefined type – an array containing a single element with the integer value ’42’.

var b = new { a =  42 };

Creates a new compiler generated type – consisting of a single field, decorated with the value ‘a’, of the integer type. This instance contains the value ’42’ in its ‘a’ field.

The rest of the post will focus solely on the former construct.

Continue reading