<p>How would you dynamically subscribe to a C# event so that given a Object instance and a String name containing the name of the event, you subscribe to that event and do something (write to the console for example) when that event has been fired?</p>

<p>It would seem using Reflection this isn't possible and I would like to avoid having to use Reflection.Emit if possible, as this currently (to me) seems like the only way of doing it.</p>

<p><strong>/EDIT:</strong> I do not know the signature of the delegate needed for the event, this is the core of the problem</p>

<p><strong>/EDIT 2:</strong> Although delegate contravariance seems like a good plan, I can not make the assumption necessary to use this solution</p>

[{'answer_id': 45795, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 0, 'selected': False, 'text': '<p>What you want can be achieved using dependency injection. For example <a href="http://msdn.microsoft.com/en-us/library/aa480450.aspx" rel="nofollow noreferrer">Microsoft Composite UI app block</a> does exactly what you described</p>\n'}, {'answer_id': 45797, 'author': 'Nick Berardi', 'author_id': 17, 'author_profile': 'https://Stackoverflow.com/users/17', 'pm_score': 2, 'selected': False, 'text': '<p>It is possible to subscribe to an event using Reflection</p>\n\n<pre><code>var o = new SomeObjectWithEvent;\no.GetType().GetEvent("SomeEvent").AddEventHandler(...);\n</code></pre>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/system.reflection.eventinfo.addeventhandler.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.reflection.eventinfo.addeventhandler.aspx</a></p>\n\n<p>Now here is going to be the problem that you are going to have to solve.  The delegates required for each event handler will have different signatures.  You are going to have to find away to create these methods dynamically, which probably means Reflection.Emit, or you are going to have to limit your self to a certain delegate so that you can handle it with compiled code.</p>\n\n<p>Hope this helps.</p>\n'}, {'answer_id': 45804, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': -1, 'selected': False, 'text': "<p>Do you mean something like:</p>\n\n<pre><code>//reflect out the method to fire as a delegate\nEventHandler eventDelegate = \n   ( EventHandler ) Delegate.CreateDelegate(\n       typeof( EventHandler ),    //type of event delegate\n       objectWithEventSubscriber, //instance of the object with the matching method\n       eventSubscriberMethodName, //the name of the method\n       true );\n</code></pre>\n\n<p>This doesn't do the subscription, but will give to the method to call.</p>\n\n<p>Edit: </p>\n\n<p>Post was clarified after this answer, my example won't help if you don't know the type. </p>\n\n<p>However all events in .Net should follow the default event pattern, so as long as you've followed it this will work with the basic EventHandler.</p>\n"}, {'answer_id': 45806, 'author': 'Erick Sgarbi', 'author_id': 4171, 'author_profile': 'https://Stackoverflow.com/users/4171', 'pm_score': 2, 'selected': False, 'text': '<pre><code>public TestForm()\n{\n    Button b = new Button();\n\n    this.Controls.Add(b);\n\n    MethodInfo method = typeof(TestForm).GetMethod("Clickbutton",\n    BindingFlags.NonPublic | BindingFlags.Instance);\n    Type type = typeof(EventHandler);\n\n    Delegate handler = Delegate.CreateDelegate(type, this, method);\n\n    EventInfo eventInfo = cbo.GetType().GetEvent("Click");\n\n    eventInfo.AddEventHandler(b, handler);\n\n}\n\nvoid Clickbutton(object sender, System.EventArgs e)\n{\n    // Code here\n}\n</code></pre>\n'}, {'answer_id': 45901, 'author': 'Mark Cidade', 'author_id': 1659, 'author_profile': 'https://Stackoverflow.com/users/1659', 'pm_score': 6, 'selected': True, 'text': '<p>You can compile expression trees to use void methods without any arguments as event handlers for events of any type. To accommodate other event handler types, you have to map the event handler\'s parameters to the events somehow.   </p>\n\n<pre><code> using System;\n using System.Linq;\n using System.Linq.Expressions;\n using System.Reflection;\n\n class ExampleEventArgs : EventArgs\n {\n    public int IntArg {get; set;}\n }\n\n class EventRaiser\n { \n     public event EventHandler SomethingHappened;\n     public event EventHandler&lt;ExampleEventArgs&gt; SomethingHappenedWithArg;\n\n     public void RaiseEvents()\n     {\n         if (SomethingHappened!=null) SomethingHappened(this, EventArgs.Empty);\n\n         if (SomethingHappenedWithArg!=null) \n         {\n            SomethingHappenedWithArg(this, new ExampleEventArgs{IntArg = 5});\n         }\n     }\n }\n\n class Handler\n { \n     public void HandleEvent() { Console.WriteLine("Handler.HandleEvent() called.");}\n     public void HandleEventWithArg(int arg) { Console.WriteLine("Arg: {0}",arg);    }\n }\n\n static class EventProxy\n { \n     //void delegates with no parameters\n     static public Delegate Create(EventInfo evt, Action d)\n     { \n         var handlerType = evt.EventHandlerType;\n         var eventParams = handlerType.GetMethod("Invoke").GetParameters();\n\n         //lambda: (object x0, EventArgs x1) =&gt; d()\n         var parameters = eventParams.Select(p=&gt;Expression.Parameter(p.ParameterType,"x"));\n         var body = Expression.Call(Expression.Constant(d),d.GetType().GetMethod("Invoke"));\n         var lambda = Expression.Lambda(body,parameters.ToArray());\n         return Delegate.CreateDelegate(handlerType, lambda.Compile(), "Invoke", false);\n     }\n\n     //void delegate with one parameter\n     static public Delegate Create&lt;T&gt;(EventInfo evt, Action&lt;T&gt; d)\n     {\n         var handlerType = evt.EventHandlerType;\n         var eventParams = handlerType.GetMethod("Invoke").GetParameters();\n\n         //lambda: (object x0, ExampleEventArgs x1) =&gt; d(x1.IntArg)\n         var parameters = eventParams.Select(p=&gt;Expression.Parameter(p.ParameterType,"x")).ToArray();\n         var arg    = getArgExpression(parameters[1], typeof(T));\n         var body   = Expression.Call(Expression.Constant(d),d.GetType().GetMethod("Invoke"), arg);\n         var lambda = Expression.Lambda(body,parameters);\n         return Delegate.CreateDelegate(handlerType, lambda.Compile(), "Invoke", false);\n     }\n\n     //returns an expression that represents an argument to be passed to the delegate\n     static Expression getArgExpression(ParameterExpression eventArgs, Type handlerArgType)\n     {\n        if (eventArgs.Type==typeof(ExampleEventArgs) &amp;&amp; handlerArgType==typeof(int))\n        {\n           //"x1.IntArg"\n           var memberInfo = eventArgs.Type.GetMember("IntArg")[0];\n           return Expression.MakeMemberAccess(eventArgs,memberInfo);\n        }\n\n        throw new NotSupportedException(eventArgs+"-&gt;"+handlerArgType);\n     }\n }\n\n\n static class Test\n {\n     public static void Main()\n     { \n        var raiser  = new EventRaiser();\n        var handler = new Handler();\n\n        //void delegate with no parameters\n        string eventName = "SomethingHappened";\n        var eventinfo = raiser.GetType().GetEvent(eventName);\n        eventinfo.AddEventHandler(raiser,EventProxy.Create(eventinfo,handler.HandleEvent));\n\n        //void delegate with one parameter\n        string eventName2 = "SomethingHappenedWithArg";\n        var eventInfo2 = raiser.GetType().GetEvent(eventName2);\n        eventInfo2.AddEventHandler(raiser,EventProxy.Create&lt;int&gt;(eventInfo2,handler.HandleEventWithArg));\n\n        //or even just:\n        eventinfo.AddEventHandler(raiser,EventProxy.Create(eventinfo,()=&gt;Console.WriteLine("!")));  \n        eventInfo2.AddEventHandler(raiser,EventProxy.Create&lt;int&gt;(eventInfo2,i=&gt;Console.WriteLine(i+"!")));\n\n        raiser.RaiseEvents();\n     }\n }\n</code></pre>\n'}, {'answer_id': 45913, 'author': 'Matt Bishop', 'author_id': 4301, 'author_profile': 'https://Stackoverflow.com/users/4301', 'pm_score': 3, 'selected': False, 'text': '<p>It\'s not a completely general solution, but if all your events are of the form \nvoid Foo(object o, T args) , where T derives from EventArgs, then you can use delegate contravariance to get away with it. Like this (where the signature of KeyDown is not the same as that of Click) :</p>\n\n<pre><code>    public Form1()\n    {\n        Button b = new Button();\n        TextBox tb = new TextBox();\n\n        this.Controls.Add(b);\n        this.Controls.Add(tb);\n        WireUp(b, "Click", "Clickbutton");\n        WireUp(tb, "KeyDown", "Clickbutton");\n    }\n\n    void WireUp(object o, string eventname, string methodname)\n    {\n        EventInfo ei = o.GetType().GetEvent(eventname);\n\n        MethodInfo mi = this.GetType().GetMethod(methodname, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);\n\n        Delegate del = Delegate.CreateDelegate(ei.EventHandlerType, this, mi);\n\n        ei.AddEventHandler(o, del);\n\n    }\n    void Clickbutton(object sender, System.EventArgs e)\n    {\n        MessageBox.Show("hello!");\n    }\n</code></pre>\n'}, {'answer_id': 376958, 'author': 'plaureano', 'author_id': 46265, 'author_profile': 'https://Stackoverflow.com/users/46265', 'pm_score': 2, 'selected': False, 'text': '<p>Try LinFu--it has a universal event handler that lets you bind to any event at runtime. For example, here\'s you you can bind a handler to the Click event of a dynamic button:</p>\n\n<pre>\n// Note: The CustomDelegate signature is defined as:\n// public delegate object CustomDelegate(params object[] args);\nCustomDelegate handler = delegate\n                         {\n                           Console.WriteLine("Button Clicked!");\n                           return null;\n                         };\n\nButton myButton = new Button();\n// Connect the handler to the event\nEventBinder.BindToEvent("Click", myButton, handler);\n</pre>\n\n<p>LinFu lets you bind your handlers to any event, regardless of the delegate signature. Enjoy!</p>\n\n<p>You can find it here: \n<a href="http://www.codeproject.com/KB/cs/LinFuPart3.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/cs/LinFuPart3.aspx</a></p>\n'}, {'answer_id': 2693383, 'author': 'Tim Lloyd', 'author_id': 189516, 'author_profile': 'https://Stackoverflow.com/users/189516', 'pm_score': 1, 'selected': False, 'text': '<p>I recently wrote a series of blog posts describing unit testing events, and one of the techniques I discuss describes dynamic event subscription. I used reflection and MSIL (code emitting) for the dynamic aspects, but this is all wrapped up nicely. Using the DynamicEvent class, events can be subscribed to dynamically like so:</p>\n\n<pre><code>EventPublisher publisher = new EventPublisher();\n\nforeach (EventInfo eventInfo in publisher.GetType().GetEvents())\n{\n    DynamicEvent.Subscribe(eventInfo, publisher, (sender, e, eventName) =&gt;\n    {\n        Console.WriteLine("Event raised: " + eventName);\n    });\n}\n</code></pre>\n\n<p>One of the features of the pattern I implemented was that it injects the event name into the call to the event handler so you know which event has been raised. Very useful for unit testing.</p>\n\n<p>The blog article is quite lengthy as it is describing an event unit testing technique, but full source code and tests are provided, and a detailed description of how dynamic event subscription was implemented is detailed in the last post.</p>\n\n<p><a href="http://gojisoft.com/blog/2010/04/22/event-sequence-unit-testing-part-1/" rel="nofollow noreferrer">http://gojisoft.com/blog/2010/04/22/event-sequence-unit-testing-part-1/</a>     </p>\n'}, {'answer_id': 49780888, 'author': 'Edward Brey', 'author_id': 145173, 'author_profile': 'https://Stackoverflow.com/users/145173', 'pm_score': 0, 'selected': False, 'text': '<p>\nThis method adds to an event, a dynamic handler that calls a method <code>OnRaised</code>, passing the event parameters as an object array:</p>\n\n<pre class="lang-cs prettyprint-override"><code>void Subscribe(object source, EventInfo ev)\n{\n    var eventParams = ev.EventHandlerType.GetMethod("Invoke").GetParameters().Select(p =&gt; Expression.Parameter(p.ParameterType)).ToArray();\n    var eventHandler = Expression.Lambda(ev.EventHandlerType,\n        Expression.Call(\n            instance: Expression.Constant(this),\n            method: typeof(EventSubscriber).GetMethod(nameof(OnRaised), BindingFlags.NonPublic | BindingFlags.Instance),\n            arg0: Expression.Constant(ev.Name),\n            arg1: Expression.NewArrayInit(typeof(object), eventParams.Select(p =&gt; Expression.Convert(p, typeof(object))))),\n        eventParams);\n    ev.AddEventHandler(source, eventHandler.Compile());\n}\n</code></pre>\n\n<p><code>OnRaised</code> has this signature:</p>\n\n<pre class="lang-cs prettyprint-override"><code>void OnRaised(string name, object[] parameters);\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/45779', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1111/']