I want to hook up a generic delegate at runtime, you can check the sample code below.
However on binding delegate to event with Delegate.CreateInstance I am getting an ArgumentException (‘Error binding to target method.’).
class MyClass
{
public event EventHandler<MyEventArgs> OnRequest;
}
class MyEventArgs : EventArgs { }
class Program
{
static void Main(string[] args)
{
MyClass obj = new MyClass();
EventInfo eventInfo = obj.GetType().GetEvent("OnRequest");
Type delegateType = eventInfo.EventHandlerType;
MethodInfo methodInfo = typeof(Program).GetMethod("OnRequestReceived");
Delegate del = Delegate.CreateDelegate(delegateType, methodInfo);
}
public static void OnRequestReceived(object o, EventArgs e) { }
}
When you create a delegate for a static method you need to pass
nullinstead of an object instance and if you were creating for an instance method it would have to be a reference to an instance of the object that defines the handler method and not an instance of the object that defines the event.In this scenario you could simplify even further and just use the overload that required only the delegate type and method info.
Also note, that in the sample code you provided you’re just creating the delegate and not actually attaching it to the event. In order to bind it to the event you also need to the following: