0

I know a way to easily subscribe to events with Reflection, but now I am wondering is there a way to do the same thing with degates. Basically I need to call the '+=' operator of a delegate using Reflection. Here is a code snippet:

using System;

class Foo 
{
    public event Action Action1;
    public Action Action2;

    public void Call() 
    {
        Action1?.Invoke();
        Action2?.Invoke();
    }
}

class Program
{
    static void Main()
    {
        var foo = new Foo();

        // Subscribing to the event Action1 
        var eventInfo = typeof(Foo).GetEvent("Action1");
        Action tmp = () => { Console.WriteLine("Hello"); };
        var args = new object[] { tmp };
        eventInfo.AddMethod?.Invoke(foo, args);

        // Subscribing to the delegate Action2 with the += operator.
        // How can I do this with Reflection, instead ???
        foo.Action2 += () => { Console.WriteLine("Bye"); };

        foo.Call();
    }
}


Output:
Hello
Bye

I need to subscribe to Action2 using Reflection (in case Action2 was a private method, for instance). Any ideas how can I achieve this? Thanks in advance!

brick
  • 113
  • 3
  • 1
    Search for "c# reflection _add event handler_" to find questions like https://stackoverflow.com/q/1121441/2864740 (there are several code examples/projects found online when using these terms) – user2864740 Sep 02 '20 at 20:45
  • Does this answer your question? [AddEventHandler using reflection](https://stackoverflow.com/questions/1121441/addeventhandler-using-reflection) – ChilliPenguin Sep 02 '20 at 20:53
  • These don't really cover my case. Please, notice that `Foo.Action2` is not an event! I can't extract `EventInfo` for it from the `Foo` class. Or at least, I don't know how to get an `EventInfo` for it... – brick Sep 02 '20 at 22:31
  • 1
    You can go to sharplab.io, see how your current code is compiled. You will see `+=` results in a `Delegate.Combine(...)` call. You can call this method manually or with reflection too. – thehennyy Sep 03 '20 at 06:28
  • This is really helpful! Thank you! – brick Sep 03 '20 at 10:13

0 Answers0