Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 35845
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 10, 20262026-05-10T14:18:00+00:00 2026-05-10T14:18:00+00:00

How would you dynamically subscribe to a C# event so that given a Object

  • 0

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?

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.

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

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

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-10T14:18:00+00:00Added an answer on May 10, 2026 at 2:18 pm

    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.

     using System;  using System.Linq;  using System.Linq.Expressions;  using System.Reflection;   class ExampleEventArgs : EventArgs  {     public int IntArg {get; set;}  }   class EventRaiser  {       public event EventHandler SomethingHappened;      public event EventHandler<ExampleEventArgs> SomethingHappenedWithArg;       public void RaiseEvents()      {          if (SomethingHappened!=null) SomethingHappened(this, EventArgs.Empty);           if (SomethingHappenedWithArg!=null)           {             SomethingHappenedWithArg(this, new ExampleEventArgs{IntArg = 5});          }      }  }   class Handler  {       public void HandleEvent() { Console.WriteLine('Handler.HandleEvent() called.');}      public void HandleEventWithArg(int arg) { Console.WriteLine('Arg: {0}',arg);    }  }   static class EventProxy  {       //void delegates with no parameters      static public Delegate Create(EventInfo evt, Action d)      {           var handlerType = evt.EventHandlerType;          var eventParams = handlerType.GetMethod('Invoke').GetParameters();           //lambda: (object x0, EventArgs x1) => d()          var parameters = eventParams.Select(p=>Expression.Parameter(p.ParameterType,'x'));          var body = Expression.Call(Expression.Constant(d),d.GetType().GetMethod('Invoke'));          var lambda = Expression.Lambda(body,parameters.ToArray());          return Delegate.CreateDelegate(handlerType, lambda.Compile(), 'Invoke', false);      }       //void delegate with one parameter      static public Delegate Create<T>(EventInfo evt, Action<T> d)      {          var handlerType = evt.EventHandlerType;          var eventParams = handlerType.GetMethod('Invoke').GetParameters();           //lambda: (object x0, ExampleEventArgs x1) => d(x1.IntArg)          var parameters = eventParams.Select(p=>Expression.Parameter(p.ParameterType,'x')).ToArray();          var arg    = getArgExpression(parameters[1], typeof(T));          var body   = Expression.Call(Expression.Constant(d),d.GetType().GetMethod('Invoke'), arg);          var lambda = Expression.Lambda(body,parameters);          return Delegate.CreateDelegate(handlerType, lambda.Compile(), 'Invoke', false);      }       //returns an expression that represents an argument to be passed to the delegate      static Expression getArgExpression(ParameterExpression eventArgs, Type handlerArgType)      {         if (eventArgs.Type==typeof(ExampleEventArgs) && handlerArgType==typeof(int))         {            //'x1.IntArg'            var memberInfo = eventArgs.Type.GetMember('IntArg')[0];            return Expression.MakeMemberAccess(eventArgs,memberInfo);         }          throw new NotSupportedException(eventArgs+'->'+handlerArgType);      }  }    static class Test  {      public static void Main()      {          var raiser  = new EventRaiser();         var handler = new Handler();          //void delegate with no parameters         string eventName = 'SomethingHappened';         var eventinfo = raiser.GetType().GetEvent(eventName);         eventinfo.AddEventHandler(raiser,EventProxy.Create(eventinfo,handler.HandleEvent));          //void delegate with one parameter         string eventName2 = 'SomethingHappenedWithArg';         var eventInfo2 = raiser.GetType().GetEvent(eventName2);         eventInfo2.AddEventHandler(raiser,EventProxy.Create<int>(eventInfo2,handler.HandleEventWithArg));          //or even just:         eventinfo.AddEventHandler(raiser,EventProxy.Create(eventinfo,()=>Console.WriteLine('!')));           eventInfo2.AddEventHandler(raiser,EventProxy.Create<int>(eventInfo2,i=>Console.WriteLine(i+'!')));          raiser.RaiseEvents();      }  } 
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 70k
  • Answers 70k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • added an answer A glossary will go a long way. Make sure that… May 11, 2026 at 12:59 pm
  • added an answer I think (?<!\() is what you meant. If the match… May 11, 2026 at 12:59 pm
  • added an answer No it does not exist. Many libraries provide it however… May 11, 2026 at 12:59 pm

Related Questions

How would you manage the lifecycle and automated build process when some of the
How would you determine the column name (e.g. AQ or BH) of the nth
How would you attach a propertychanged callback to a property that is inherited? Like
How would you reccommend handling RSS Feeds in ASP.NET MVC? Using a third party
Here is a simple overview of my directory layout for my views: Project Page
[I'm not asking about the architecture of SO, but it would be helpful to
Assume you are designing and implementing a new language from scratch, though you may
Most of my C/C++ development involves monolithic module files and absolutely no classes whatsoever,

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.