#649 – Creating an Anonymous Type

An anonymous type is a temporary data type that is inferred based on the data that you include in an object initializer.

We can use object initializer syntax to initialize an object:

Dog kirby = new Dog { Name="Kirby", Age=14 };

We can use the same syntax to initialize an object where we don’t mention a particular data type.  For example, we can declare/initialize an object that contains some information about a movie.

var movie = new { Title = "North By Northwest", Year = 1959, Director = "Alfred Hitchcock" };

Notice that we haven’t created a Movie class, but we now have an object that represents a movie which has three properties–Title, Year and Director.

The compiler has actually created a temporary “anonymous” type to represent the movie object.  Note also that the movie variable is implicitly typed (var keyword)since we don’t have a named type.

Advertisement