Home > Programming > IDictionary from anonymous type

IDictionary from anonymous type

In ASP.NET MVC, we can specify what attributes appear on our HTML elements by passing an anonymous type as an argument.

@Html.TextBox("my-textbox", "hello world", new { @class = "css-class", custom = "custom" })

In this example, we’re specifying that the input element will have a class attribute and a custom attribute when rendered.

Inspired by this, I needed a way to convert an anonymous type to an IDictionary<string, object>. I created this extension method that allows an object to be converted to a dictionary.

public static class ExtensionMethods
    public static IDictionary<string, object> ToDictionary(this object data)
        BindingFlags publicAttributes = BindingFlags.Public | BindingFlags.Instance;
        Dictionary<string, object> dictionary = new Dictionary<string, object>();

        foreach (PropertyInfo property in data.GetType().GetProperties(publicAttributes))
            if (property.CanRead)
                dictionary.Add(property.Name, property.GetValue(data, null));

        return dictionary;

This extends the object type and adds a ToDictionary extension method.

var anonymous = new { First = "John", Last = "Doe" };
IDictionary<string, object> dictionary = anonymous.ToDictionary();

Alternately, if we’re working in an ASP.NET MVC project, we can use RouteValueDictionary to convert an anonymous type to a dictionary.

var anonymous = new { First = "John", Last = "Doe" };
RouteValueDictionary dictionary = new RouteValueDictionary(anonymous);

string firstName = dictionary["First"].ToString();
string lastName = dictionary["Last"].ToString();
  1. David Kemp
    April 20, 2011 at 10:08 am

    Thanks – that just saved me 20 minutes with the compiler

  2. April 29, 2011 at 11:00 am

    Awesome. Found just what I was looking for!

  3. May 12, 2011 at 8:47 am

    Not to rain on your parade too much this is available directly from .NET


    What’s really cool is when you use this in combination with the TagBuilder class

    var tagBuilder = new TagBuilder(“input”);

    tagBuilder.MergeAttribute(“type”, “hidden”);
    tagBuilder.MergeAttribute(“name”, inputName);


    if (value != null)
    tagBuilder.MergeAttribute(“value”, value.ToString());

    if (htmlAttributes != null) tagBuilder.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes), replaceExisting: true);

    • May 12, 2011 at 10:08 am

      Thank you dotnetchris, I did not know about that method.

      But my original intent was to create an extension method for non-ASP.NET projects, such as window services or console applications. For those cases, I may not want to reference the System.Web.Mvc assembly in order to use the HtmlHelper. For example, I may be deploying a service to an environment where ASP.NET MVC is not installed, since it’s not part of the default .NET installation. There may also be other cases where my projects have not been upgraded to .NET 4.0 yet.

      • May 19, 2011 at 1:55 pm

        The MVC dependency is a semi-valid concern, however with VS2010 SP1 it’s easily overcome. You can use “deployable dependencies” that basically just puts the MVC dll in your bin directory when you publish.

        On the pragmatist side I can understand not wanting a web dependency in an executable.

        I’m not 100% sure which MVC this was added in whether it’s from 2 or 3, so it might only require a dependency on .NET3.5.

        Of course with this being said I feel bad for any company that has such a bad handle on their technology usage that they can’t forward migrate to .NET4 because there’s really almost no justifiable reason to not be using 4.

  4. Phil Cooper
    August 2, 2011 at 3:05 pm

    There is a valid reason for a business not to upgrade, in fact there are 2. Time & money. If you have a test and building environment based on the 2/3.5 framework it takes time to upgrade all of these. It’s difficult trying to justify this time and money to any non-technical person espeically when the benefits aren’t immediately tangible.

  5. August 2, 2011 at 5:02 pm

    Any business that hamstrings their software developers with legacy technology is asking for failure. You can’t expect success when you make erroneous decisions to justify any reason for not using the latest version of .NET.

  6. July 28, 2017 at 11:21 am

    Hello blogger, i must say you have high quality content here.
    Your page should go viral. You need initial traffic only.
    How to get it? Search for; Mertiso’s tips go viral

  1. No trackbacks yet.

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

%d bloggers like this: