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

  • SEARCH
  • Home
  • 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 7703601
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T23:29:48+00:00 2026-05-31T23:29:48+00:00

is it possible to generate an eventhandler while running? I want to do something

  • 0

is it possible to generate an eventhandler while running?
I want to do something like that:

public bool addCallback(string name, Delegate Callback)
{
   EventInfo ei = DataProxy.GetType().GetEvent(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
   if (ei == null)
      return false;
   ei.AddEventHandler(DataProxy, Callback);
   //now I want to add an Eventhandler, which removes the Callback and this new Eventhandler itsself
   return true;
}
  • 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. Editorial Team
    Editorial Team
    2026-05-31T23:29:49+00:00Added an answer on May 31, 2026 at 11:29 pm

    (I am not 100% sure I understand what you are going to hook your generated event handler to from the example, but here’s the easiest way I know of for creating an event handler)

    Depends on your platform and trust level. The most flexible way of doing it is to use Emit to generate the method (see here).

    However, I found a relatively easy to use and good alternative to be generated Linq expressions (here’s the namespace help).

    The idea is fairly simple:

    1. Use the various Expression-derived classes you can see in the namespace to define what your callback is doing. In this case, you want to generate something that calls .RemoveEventHandler (I am guessing) on the ei instance (specifically, you will use the ConstantExpression to create a ref to your ei variable and to your Callback parameter and a MethodCallExpression to create a call to the RemoveDataHandler method).

    2. Once you create the expression that does what you need, you need to create a delegate (Lambda) out of it (see here)

    3. Almost done. You still need to compile the lambda, which you do by calling .Compile on the object you got from the previous step (see here)

    Edit: This is a Windows console example of a dynamically generated delegate that removes itself. Note that WP7 Linq expression support is more limited than .NET 4.0 and so you will need to adjust it (make helper methods that will do some of the work and call them from the expression instead of what I did).

    Edit2: BTW: The mechanism by which the lambda can remove itself, is to create another lambda that returns a local variable that is of that type. After creating the lambda, save it to the local variable and run the code (I am not sure if this would have worked without the secondary lambda)

    Edit3: No – you have to use the delegate trick, otherwise, the constant gets “frozen” and will not update as you would want it to. So the code as is works.

    public class MyEventArgs : EventArgs
    {
    }
    
    public class EventContainer
    {
        public event EventHandler<MyEventArgs> MyEvent;
    
        public void Fire()
        {
            Console.WriteLine("Firing");
            if (MyEvent != null)
            {
                MyEvent(this, new MyEventArgs());
            }
            Console.WriteLine("Fired");
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            EventContainer container = new EventContainer();
            var adder = container.GetType().GetMethod("add_MyEvent");
            var remover = container.GetType().GetMethod("remove_MyEvent");
    
            object self = null;
            Func<object> getSelf = () => self;
    
            var block = Expression.Block(
                // Call something to output to console.
                Expression.Call(
                    null,
                    typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }),
                    Expression.Constant("Event called")),
                // Now call the remove_Event method.
                Expression.Call(
                    Expression.Constant(container), // passing the container as "this"
                    remover, // And the remover as the method info
                    Expression.Convert( // we need to cast the result of getSelf to the correct type to pass as an argument
                        Expression.Invoke( // For the parameter (what to convert), we need to call getSelf
                            Expression.Constant(getSelf)), // So this is a ref to getSelf
                        adder.GetParameters()[0].ParameterType) // finally, say what to convert to.
                   ) 
               );
    
            // Create a lambda of the correct type.
            var lambda = Expression.Lambda(
                adder.GetParameters()[0].ParameterType, 
                block, 
                Expression.Parameter(typeof(object)), 
                Expression.Parameter(typeof(MyEventArgs)));
            var del = lambda.Compile();
    
            // Make sure "self" knows what the delegate is (so our generated code can remove it)
            self = del;
    
    
            // Add the event.
            adder.Invoke(container, new object[] { del });
    
            // Fire once - see that delegate is being called.
            container.Fire();
    
            // Fire twice - see that the delegate was removed.
            container.Fire();
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Is it possible to generate a new image name for each image that is
While it is possible to generate PowerPoint presentations automatically using Office Automation , this
Is it possible to generate a random number between 2 doubles? Example: public double
Is it possible to generate a LaTeX document through Sweave that don't have the
Is it possible to generate a top 10 of fans of a page that
Is it possible to generate a property with a public getter and a protected
Is it possible to generate a BLOB string of a bitmap image which using
Possible Duplicate: Generate a Hash from string in Javascript/jQuery Can anyone suggest a simple
Possible Duplicate: Generate list of all possible permutations of a string I need to
Possible Duplicate: Generate certificates, public and private keys with Java I need to generate

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.