C#: 4.0 Anonymous Types

Simple, elegant data storage.

One of the latest improvements to the .NET Framework in 4.0 is the ability to use object initializers to create simple data-storage objects without having to create a class or struct. Also, these anonymously-typed objects are created by the compiler so you still have strong-typing on your data.
Once the properties have been defined in the initializer, you get/set them simply using the dot-notation.
Anonymous Types provide “type inference” – using the var keyword to define a local variable without explicitly specifying a variable type.
In this example, I will begin by defining a generic (no pun intended) Anonymous Type to store three test values for first and last name, and the phone number.

1-anonymous-types

Next, I’ll define an array of Anonymous Types and store the contents in a StringBuilder object for writing back to the View.

2-anonymous-types

In order to display the contents of Anonymous Types from the homepage, I’ll use the Html.ActionLink() method to call my AnonymousTypes controller’s Index action method.

3-anonymous-types

 

4-anonymous-types

 

By clicking the homepage “Anonymous Types” link, I see the results of my work.

5-anonymous-types

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 )

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