0

In C#, how can I create a dynamic method that can be used to handle an event?

Here is an event:

public event EventHandler<EventArgs> refresh;

Here is a method:

public void Test()
{

}

How can I dynamically create a method to handle the refresh event, such that the dynamic method calls the Test method?

The Test method above is an example of a method to be called.

Simon
  • 7,991
  • 21
  • 83
  • 163

2 Answers2

0

Well, you could simply subscribe to the event.

public class SomeClass
{
    public event EventHandler<EventArgs> refresh;
}

public void Test()
{
}

void Main()
{
    var some = new SomeClass();
    some.refresh += (sender, e) => Test();
    // or
    some.refresh += Refreshed;
}

void Refreshed(object sender, EventArgs e)
{
    Test();
}
Kinetic
  • 2,640
  • 17
  • 35
  • This is what I am wanting to do, but I am in need of help on how to create the "Refreshed" method dynamically. – Simon Jul 01 '16 at 03:37
  • Can't you tell us why it need to be created dynamically? – Kinetic Jul 01 '16 at 03:40
  • The "Test' method is an example of a method than can be called. A user can choose any method to be called. As such, it has to be created dynamically. – Simon Jul 01 '16 at 03:43
  • 4
    I guess that's the kind of information I would write in a question. – Kinetic Jul 01 '16 at 03:44
  • 1
    @user3736648 if "A user can choose any method to be called" ie. a drop down list, you could drop all subscribed events ([See here for some pre-baked code](https://stackoverflow.com/questions/91778/how-to-remove-all-event-handlers-from-a-control)), then subscribe to the selected method `some.refresh += (sender, e) => ChoosenMethod();`. Is this what you mean by dynamic? – Bennett Yeo Jul 01 '16 at 03:57
0

If the method you want to invoke is an instance method in some class and you have an instance of that class and the name of the method, you can use Delegate.CreateDelegate() to create a delegate to that method and then use a lambda to invoke it in an event handler:

static EventHandler<EventArgs> CreateHandler(object methodObject, string methodName)
{
    var methodDelegate =
        (Action)Delegate.CreateDelegate(typeof(Action), methodObject, methodName);

    return (s, e) => methodDelegate();
}

Usage can then look like this (assuming Test is in class C):

refresh += CreateHandler(new C(), "Test");

refresh(this, EventArgs.Empty);
svick
  • 236,525
  • 50
  • 385
  • 514