Passing anonymous type as method parameters

Use dynamic object for parameters if you want to pass an anonymous type. The execute method of a plugin should expect certain properties of a parameter object in order to work. By using dynamic keyword C# compiler will be instructed to not perform type check on a parameter and will allow to use strongly-typed syntax in the plugin code. The properties name resolution will happen in run-time and if a passed object did not have such properties an exception will be thrown.

var o = new { FirstName = "John", LastName = "Doe" };

var result = MyMethod(o);

string MyMethod(dynamic o)
{
    return o.FirstName + " " + o.LastName;
}

Read more in this blog post


There are some ways to make this possible although I wouldn't advice any of them.

First, you can use reflection which means you have to write a lot of additional (error-prone) code in your PluginService.Execute method to get the values you want.

Second, if you know the parameters of the anonymous type you are passing to your method you can use the technique described here. You can cast to another anonymous type inside your method that has the same properties. Here is another description of the same technique from Jon Skeet.

Third, you can use classes from the System.ComponentModel. For example, ASP.NET MVC uses this. It uses reflection under the hood. However, in ASP.NET MVC either the property names are well-known (controller and action for example) or their names don't matter because they are passed as-is to a controller method (id for example).


I did eventually come across this post that demonstrates using anonymous types as dictionaries. Using this method you could pass the anonymous type as a method parameter (object) and access it's properties.

However, I would also add that after looking into the new dynamic features in .net 4.0 such as the ExpandoObject, it feels much cleaner to pass a dynamic object as a parameter:

        dynamic myobj = new ExpandoObject();
        myobj.FirstName = "John";
        myobj.LastName = "Smith";

        SayHello(myobj);
        ...........

        public static void SayHello(dynamic properties)
        {
           Console.WriteLine(properties.FirstName + " " + properties.LastName);
        }