Working with C# Anonymous objects

Anonymous objects in C# are very handy, especially given the way they are supported by the ASP.NET MVC framework.

I recently ran into a case where I wanted to interact with an anonymous object. Specifically, I was testing the data that I provided a JsonResult. I handed the JsonResult a pretty complicated anonymous object with several layers of nesting. This is a great use of anonymous objects because in code they look a lot like JSON. So, how do I make sure that the JsonResult is getting the correct data? The answer is reflection. But like with all things, there is a hard way and an easy way.

First the hard way.

var example = new {
  stringData = "string data",
  integerData = 12,
  booleanData = true
}

Given the block of code above, if we want to retrieve one of the values from the example instance we have to do the following.

string value = (string) example.GetType().
  InvokeMember(
    "stringData",
    BindingFlags.GetProperty,
    null,
    example,
    new object[] { });

Replace “stringData” with the name of any of the fields and there you go. The trouble is that this block of code is seven kinds of ugly (yes, I counted) and it is not the kind of thing that you want to type over and over. Wouldn’t it be nice if there was an easier way?

What if we use the following extension class. Also available as a gist on my github account.

static class ObjectExtensions
{
    public static T Property<t>(this object target, string name)
    {
        return (T)target.GetType().InvokeMember(
            name,
            BindingFlags.GetProperty,
            null,
            target,
            new object[] { });
    }
}

Now we can access fields from our sample class by writing the following code.

string value = example.Property<string>("stringData");
int otherValue = example.Property<int>("integerData");
bool yetAnother = example.Property<bool>("booleanData");

I think that this looks much better. I hope this helps you as much as it has helped me.

Tags:

Leave a Reply