#650 – Creating an Array of Anonymously-Typed Objects

An anonymous type is a temporary data type that is inferred based on the data that you include in an object initializer.  In addition to creating a single anonymously-typed object with an object initializer, you can also create an array of objects.

            var movies = new[] {
                new { Title = "North By Northwest", Year = 1959, Director = "Alfred Hitchcock" },
                new { Title = "Zelig", Year = 1983, Director = "Woody Allen" },
                new { Title = "King Kong", Year = 2005, Director = "Peter Jackson" }};

With this declaration, you end up with an array of anonymously-typed objects, each of which has the properties Title, Year, and Direction.

Note that this implicitly-typed array must contain elements of the same type, so each element must have the exact  same set of properties.

Advertisement

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

One Response to #650 – Creating an Array of Anonymously-Typed Objects

  1. Pingback: #775 – Copying an Array of Anonymously-Typed Objects « 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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: