The product of a web developer with a little too much caffeine

Simplify Using Anonymous Types

with 7 comments

New Version Available:Check out this post about the AnonymousType class Remixed!.

When you’re using ASP.NET MVC you pass information from the Controller to the View. Your information is found in the ViewDataDictionary where you can cast the info back into whatever form it originally was. Additionally, you can even specify a model type for the page so that no casting is required to access your information.

It may be a little inconvenient, but it’s not bad. This just means you need to either define the class in advance or limit yourself to simple values.

If you’re writing LINQ queries and creating anonymous types then you’re in a tougher situation. I’ve seen people try and come up with solutions for accessing an anonymous type after its been created, but nothing seemed all that intuitive.

In the next version of C# we’re going to see the new dynamic declaration which will most likely solve this problem. For now, Reflection is about the only way you solve this issue.

On a recent project I got a little tired of trying to manually do this each time. I ended up writing a wrapper class (included at the end of the post). The example below shows how you can use this class AnonymousType.

this.ViewData["details"] = new {
  name = "Jim",
  age = 30

AnonymousType details = new AnonymousType(this.ViewData["details"]);

//access properties
string name = details.Get<string>("name");
int age = details.Get<int>("age");

//supply a default type in case the property doesn't exist
bool fake = details.Get<bool>("someFakeProperty", false);

//Use the properties by name - maps to the argument name
details.Use((string name, int age) => { 
  Console.WriteLine("{0} is {1} years old", name, age);

//An wrong property name (wrong type or incorrect case) will cause an error
details.Use((int NAME) => { /* Error! */ });

It’s really just Reflection, but it streamlines using unknown types inside of a View.

Now, if you are thinking “What about methods? or Fields?” then you’re like me. Now, if your second thought was “Well wait, if it has methods then it’s a defined class, we should just cast it instead.”, then you’re much smarter than me. Unfortunately, I spent an hour or so writing ComplexAnonymousType that would call methods (even match correct signatures), access fields, the works… then to realize how much of a wasted effort it was. 🙂

Anyways, try it out if interested. Let me know what you think!

Don’t forget! Reflection is slower than the normal means of accessing properties. While the time spent is negligible in small amounts, if you’re going to be using this code below with a lot of items, it may be wiser to define a class instead.

Source Code

Download AnonymousType.cs

New Version Available:Check out this post about the AnonymousType class Remixed!.



Written by hugoware

May 13, 2009 at 11:41 am

7 Responses

Subscribe to comments with RSS.

  1. Simplify Using Anonymous Types…

    Thank you for submitting this cool story – Trackback from DotNetShoutout…


    May 18, 2009 at 9:39 pm

  2. […] to Vote[] Simplify Using Anonymous Types (5/18/2009)Monday, May 18, 2009 from jungchanSimplify Using Anonymous […]

  3. Why not .GetInt, .GetString instead of .Get ?


    May 19, 2009 at 6:55 pm

  4. You mean a separate method for each of the types?

    You could do that. In this instance I felt that generics we’re a more open ended (and a little cleaner) since you could have anything stored in a property on an Anonymous type.

    It is something to consider though as an add-on.



    May 19, 2009 at 7:31 pm

  5. Can’t Automapper handle this easily? Does it work with anonymous types ?


    May 20, 2009 at 4:05 pm

  6. At a cursory glance over Automapper (on codeplex) it looks like it handles Defined types. This is a wrapper for both Anonymous type and Defined types.

    I can’t say if Automapper can’t do this or not though since I haven’t used it before.


    May 20, 2009 at 4:22 pm

  7. […] "Assigned just like that!"; Need to add a function! something.generate = function() { … }; If you read my previous post about passing Anonymous Types, you’ll understand where the inspiration came […]

Leave a Reply

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

You are commenting using your 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: