C# – Passing anonymous type as method parameters

anonymous-typescreflection

In my plugin architecture I am currently passing a plugin name (string), method name (string) and parameters (object array) to my plugin service to execute the specified method and return the result (of type T).

The plugin service's execute method can be seen below:

public TResult Execute<TResult>(string pluginName, string operation, params object[] input) {
    MethodInfo method = null;
    TResult result = default(TResult);

    var plugin = _plugins.Enabled().FirstOrDefault(x => x.GetType().Name.Equals(pluginName,  StringComparison.InvariantCultureIgnoreCase));

    if (plugin != null) {
        method = plugin.GetType().GetMethods().FirstOrDefault(x => x.Name == operation);
        if (method != null) {
            result = (TResult)method.Invoke(plugin, input);
        }
    }
    return result;
  }

An example usage:

var url = AppHelper.PluginService.Execute<string>(
    "ImagePlugin",
    "GetImageUrl",
    new object[] { image, size });

What I would rather do is pass in an anonymous type instead (as I think this is more readable) i.e.

var url = AppHelper.PluginService.Execute<string>(
    "ImagePlugin",
    "GetImageUrl",
    new { image = image, targetSize = size });

How would I change my Execute method to map the anonymous type properties to my plugin method parameters?

I had considered using the new dynamic type in .net 4.0 but I prefer to define my parameters on the plugin method rather than accepting one dynamic object.

Thanks
Ben

[Update]

After looking through the ASP.NET MVC source code it seems simple enough to pull the anonymous type into an object dictionary e.g. RouteValueDictionary.
With the help of reflection a linq expression is created dynamically. Although its a good implementation, I didn't really want all this extra complexity.

As per the comment below, I can achieve readability just by specifying my parameters inline (no need for the object array declaration):

var url = AppHelper.PluginService.Execute<string>("ImagePlugin", "GetImageUrl", image, size);

Best Answer

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);
        }