Creating delegate from MethodInfo

You’re trying to create a delegate from an instance method, but you’re not passing in a target. You could use: Delegate.CreateDelegate(typeof(TestDelagate), this, method); … or you could make your method static. (If you need to cope with both kinds of method, you’ll need to do that conditionally, or pass in null as the middle argument.)

get methodinfo from a method reference C#

Slight adaptation of a previously posted answer, but this blog post seems to achieve what you’re asking for; http://blog.functionalfun.net/2009/10/getting-methodinfo-of-generic-method.html Sample usage would be as follows; var methodInfo = SymbolExtensions.GetMethodInfo(() => Program.Main()); Original answer was to this question; https://stackoverflow.com/a/9132588/5827

How to create a delegate from a MethodInfo when method signature cannot be known beforehand?

You can use System.Linq.Expressions.Expression.GetDelegateType method: using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; class Program { static void Main() { var writeLine = CreateDelegate(typeof(Console).GetMethod(“WriteLine”, new[] { typeof(string) })); writeLine.DynamicInvoke(“Hello world”); var readLine = CreateDelegate(typeof(Console).GetMethod(“ReadLine”, Type.EmptyTypes)); writeLine.DynamicInvoke(readLine.DynamicInvoke()); } static Delegate CreateDelegate(MethodInfo method) { if (method == null) { throw new ArgumentNullException(“method”); } if (!method.IsStatic) { throw … Read more

How can I create an Action delegate from MethodInfo?

Use Delegate.CreateDelegate: // Static method Action action = (Action) Delegate.CreateDelegate(typeof(Action), method); // Instance method (on “target”) Action action = (Action) Delegate.CreateDelegate(typeof(Action), target, method); For an Action<T> etc, just specify the appropriate delegate type everywhere. In .NET Core, Delegate.CreateDelegate doesn’t exist, but MethodInfo.CreateDelegate does: // Static method Action action = (Action) method.CreateDelegate(typeof(Action)); // Instance method (on … Read more

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 … Read more