Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing anonymous type as method parameters

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);
like image 808
Ben Foster Avatar asked Aug 08 '10 09:08

Ben Foster


People also ask

Can a method return an anonymous type C#?

As in the preceding facts you cannot return an anonymous type from a method, if you do want to return one then you need to cast it to an object.

What is the difference between an anonymous type and a regular data type?

The compiler gives them a name although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type, except that it cannot be cast to any type except for object.


3 Answers

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);         } 
like image 102
Ben Foster Avatar answered Oct 03 '22 09:10

Ben Foster


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

like image 23
Alex T. Avatar answered Oct 03 '22 09:10

Alex T.


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).

like image 29
Ronald Wildenberg Avatar answered Oct 03 '22 08:10

Ronald Wildenberg