Can you get a Func (or similar) from a MethodInfo object?

This kind of replaces my previous answer because this, although it’s a slightly longer route – gives you a quick method call and, unlike some of the other answers, allows you to pass through different instances (in case you’re going to encounter multiple instances of the same type). IF you don’t want that, check my update at the bottom (or look at Ben M’s answer).

Here’s a test method that does what you want:

public class TestType
{
  public string GetName() { return "hello world!"; }
}

[TestMethod]
public void TestMethod2()
{
  object o = new TestType();

  var input = Expression.Parameter(typeof(object), "input");
  var method = o.GetType().GetMethod("GetName", 
    System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
  //you should check for null *and* make sure the return type is string here.
  Assert.IsFalse(method == null && !method.ReturnType.Equals(typeof(string)));

  //now build a dynamic bit of code that does this:
  //(object o) => ((TestType)o).GetName();
  Func<object, string> result = Expression.Lambda<Func<object, string>>(
    Expression.Call(Expression.Convert(input, o.GetType()), method), input).Compile();

  string str = result(o);
  Assert.AreEqual("hello world!", str);
}

Once you build the delegate once – you can cache it in a Dictionary:

Dictionary<Type, Func<object, string>> _methods;

All you do then is add it to the dictionary, using the incoming object’s Type (from GetType()) as the key. In the future, you first check to see if you have a ready-baked delegate in the dictionary (and invoke it if so), otherwise you build it first, add it in, and then invoke it.

Incidentally, this is a very highly simplified version of the kind of thing that the DLR does for it’s dynamic dispatch mechanism (in C# terms, that’s when you use the ‘dynamic’ keyword).

And finally

If, as a few people have mentioned, you simply want to bake a Func bound directly to the object you receive then you do this:

[TestMethod]
public void TestMethod3()
{
  object o = new TestType();

  var method = o.GetType().GetMethod("GetName", 
    System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);

  Assert.IsFalse(method == null && !method.ReturnType.Equals(typeof(string)));

  //this time, we bake Expression.Constant(o) in.
  Func<string> result = Expression.Lambda<Func<string>>(
   Expression.Call(Expression.Constant(o), method)).Compile();

  string str = result(); //no parameter this time.
  Assert.AreEqual("hello world!", str);
}

Note, though, that once the expression tree gets thrown away, you need to make sure that the o stays in scope, otherwise you could get some nasty results. The easiest way would be to hold on to a local reference (in a class instance, perhaps) for the lifetime of your delegate. (Removed as a result of Ben M’s comments)

Leave a Comment