#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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #649 – Creating an Anonymous Type

  1. Pingback: #803 – Situations When You Might Use the var Keyword | 2,000 Things You Should Know About C#

  2. Pingback: #833 – Some Examples of Anonymous Object Initializers | 2,000 Things You Should Know About C#

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

%d bloggers like this: