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 6743793
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T12:00:18+00:00 2026-05-26T12:00:18+00:00

I’m trying to write a class that’s to be used to trigger a call

  • 0

I’m trying to write a class that’s to be used to trigger a call to a method from an arbitrary event but I’m stuck as I simply cannot figure out a way to reference ‘this’ from emitted MSIL code.

This example should describe what I’m looking for:

class MyEventTriggeringClass
{ 
    private object _parameter;

    public void Attach(object source, string eventName, object parameter)
    {
        _parameter = parameter;
        var e = source.GetType().GetEvent(eventName);
        if (e == null) return;
        hookupDelegate(source, e);
    }

    private void hookupDelegate(object source, EventInfo e)
    {
        var handlerType = e.EventHandlerType;
        // (omitted some validation here)
        var dynamicMethod = new DynamicMethod("invoker",
                  null,
                  getDelegateParameterTypes(handlerType), // (omitted this method in this exmaple)
                  GetType());
        var ilgen = dynamicMethod.GetILGenerator();
        var toBeInvoked = GetType().GetMethod(
            "invokedMethod", 
            BindingFlags.NonPublic | BindingFlags.Instance);
        ilgen.Emit(OpCodes.Ldarg_0); // <-- here's where I thought I could push 'this' (failed)
        ilgen.Emit(OpCodes.Call, toBeInvoked);
        ilgen.Emit(OpCodes.Ret);
        var sink = dynamicMethod.CreateDelegate(handlerType);
        e.AddEventHandler(source, sink);
    }

    private void invokedMethod()
    {
        Console.WriteLine("Value of _parameter = " + _parameter ?? "(null)"); 
        // output is always "(null)"
    }
}

Here’s an xample how I envision the class being used:

var handleEvent = new MyEventTriggeringClass();
handleEvent.Attach(someObject, "SomeEvent", someValueToBePassedArround);

(Please note that the above example is quite pointless. I just try to describe what I’m looking for. My final goal here is to be able to trigger a call to an arbitrary method whenever an arbitrary event fires. I’ll use that in a WPF projekt where I try to use 100% MVVM but I’ve stumbled upon one of the [seemingly] classic breaking points.)

Anyway, the code “works” so far as it successfully invoked the “invokedMethod” when the arbitrary event fires but ‘this’ seems to be an empty object (_parameter is always null). I have done some research but simply cannot find any good examples where ‘this’ is properly passed to a method being called from within a dynamic method like this.

The closest example I’ve found is THIS ARTICLE but in that example ‘this’ can be forced to the dynamic method since it’s called from the code, not an arbitrary event handler.

Any suggestions or hints would be very appreciated.

  • 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-26T12:00:19+00:00Added an answer on May 26, 2026 at 12:00 pm

    I’m gonna go ahead and answer my own question here. The solution was very simple once I realized what the real problem was: Specifying the event handler’s instance/target. This is done by adding an argument to MethodInfo.CreateDelegate().

    If you’re interested, here’s a simple example you can cut’n’paste into a console app and try it out:

    class Program
    {
        static void Main(string[] args)
        {
            var test = new MyEventTriggeringClass();
            var eventSource = new EventSource();
            test.Attach(eventSource, "SomeEvent", "Hello World!");
            eventSource.RaiseSomeEvent();
            Console.ReadLine();
        }
    }
    
    class MyEventTriggeringClass
    {
        private object _parameter;
    
        public void Attach(object eventSource, string eventName, object parameter)
        {
            _parameter = parameter;
            var sink = new DynamicMethod(
                "sink",
                null,
                new[] { typeof(object), typeof(object), typeof(EventArgs) },
                typeof(Program).Module);
    
            var eventInfo = typeof(EventSource).GetEvent("SomeEvent");
    
            var ilGenerator = sink.GetILGenerator();
            var targetMethod = GetType().GetMethod("TargetMethod", BindingFlags.Instance | BindingFlags.Public, null, new Type[0], null);
            ilGenerator.Emit(OpCodes.Ldarg_0); // <-- loads 'this' (when sink is not static)
            ilGenerator.Emit(OpCodes.Call, targetMethod);
            ilGenerator.Emit(OpCodes.Ret);
    
            // SOLUTION: pass 'this' as the delegate target...
            var handler = (EventHandler)sink.CreateDelegate(eventInfo.EventHandlerType, this);
            eventInfo.AddEventHandler(eventSource, handler);
        }
    
        public void TargetMethod()
        {
            Console.WriteLine("Value of _parameter = " + _parameter);
        }
    }
    
    class EventSource
    {
        public event EventHandler SomeEvent;
    
        public void RaiseSomeEvent()
        {
            if (SomeEvent != null)
                SomeEvent(this, new EventArgs());
        }
    }
    

    So, thanks for your comments and help. Hopefully someone learned something. I know I did.

    Cheers

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I'm trying to create an if statement in PHP that prevents a single post
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I want to count how many characters a certain string has in PHP, but
For some reason, after submitting a string like this Jack’s Spindle from a text

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.