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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T10:39:56+00:00 2026-05-20T10:39:56+00:00

I’m trying to learn a bit about dynamically generating event handlers and I’m having

  • 0

I’m trying to learn a bit about dynamically generating event handlers and I’m having difficulty trying to recreate this simple situation:

public delegate void SomethingHappenedEventHandler(object sender, object args);
public event SomethingHappenedEventHandler SomethingHappened;

// This is the event handler that I want to create dynamically
public void DoSomething(object a, object b)
{
    DoSomethingElse(a, b);
}

public void DoSomethingElse(object a, object b)
{
    Console.WriteLine("Yay! " + a + " " + b);
}

I’ve used reflector to generate the IL for the DoSomething method, and it gives me:

.method public hidebysig instance void DoSomething(object a, object b) cil managed
{
    .maxstack 8
    L_0000: ldarg.0 
    L_0001: ldarg.1 
    L_0002: ldarg.2 
    L_0003: call instance void MyNamespace::DoSomethingElse(object, object)
    L_0008: ret 
}

So, I’ve written the following code to dynamically generate and execute a method equivalent to DoSomething(…):

public void CreateDynamicHandler()
{
    var eventInfo = GetType().GetEvent("SomethingHappened");
    var eventHandlerType = eventInfo.EventHandlerType;

    var dynamicMethod = new DynamicMethod("DynamicMethod", null, new[] { typeof(object), typeof(object) }, GetType());
    var ilgen = dynamicMethod.GetILGenerator();
    ilgen.Emit(OpCodes.Ldarg_0);
    ilgen.Emit(OpCodes.Ldarg_1);
    ilgen.Emit(OpCodes.Ldarg_2);

    MethodInfo doSomethingElse = GetType().GetMethod("DoSomethingElse", new[] { typeof(object), typeof(object) });
    ilgen.Emit(OpCodes.Call, doSomethingElse);
    ilgen.Emit(OpCodes.Ret);

    Delegate emitted = dynamicMethod.CreateDelegate(eventHandlerType);
    emitted.DynamicInvoke("hello", "world");
}

However, when I run this I get an InvalidProgramException: JIT Compiler encountered an internal limitation.

Can anyone point out where I’ve gone wrong?

[EDIT] As several people have commented, the whole IL generation thing is unnecessary if I know all of the types involved. My reason for doing this is that this is the first step towards dynamically generating event handlers at runtime for events where I do not know all the types involved. Basically I’d been following the example at http://msdn.microsoft.com/en-us/library/ms228976.aspx, got stuck, and then tried to unwind things into a simple example that I could get working.

  • 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-20T10:39:56+00:00Added an answer on May 20, 2026 at 10:39 am

    It is unclear why you would want to create this method dynamically. I can’t really think of any situation in which you couldn’t just apply a lambda to the event:

    public delegate void SomethingHappenedEventHandler(object sender, object args);
    public event SomethingHappenedEventHandler SomethingHappened;
    
    public void DoSomethingElse(object a, object b)
    {
        Console.WriteLine("Yay! " + a + " " + b);
    }
    
    // If the signature exactly matches the delegate, just use the method name
    SomethingHappened += DoSomethingElse;
    
    public void DoSomethingDifferent(object a)
    {
        Console.WriteLine("Yay! " + a);
    }
    
    // Otherwise, just use a lambda expression
    SomethingHappened += (a, b) => DoSomethingDifferent(a);
    

    That said, the reason your code doesn’t work is because DynamicMethod generates only static methods. Therefore, the IL code is invalid because Ldarg_0 and Ldarg_1 load the two parameters but Ldarg_2 refers to a non-existent parameter. If I change it in the following way, it works as one would expect — it is now a static method with three parameters, where the first parameter is basically this:

    public void CreateDynamicHandler()
    {
        var dynamicMethod = new DynamicMethod("DynamicMethod", null,
            new[] { typeof(MyClass), typeof(object), typeof(object) }, typeof(MyClass));
        var ilgen = dynamicMethod.GetILGenerator();
        ilgen.Emit(OpCodes.Ldarg_0);
        ilgen.Emit(OpCodes.Ldarg_1);
        ilgen.Emit(OpCodes.Ldarg_2);
    
        MethodInfo doSomethingElse = typeof(MyClass).GetMethod("DoSomethingElse",
            new[] { typeof(object), typeof(object) });
        ilgen.Emit(OpCodes.Call, doSomethingElse);
        ilgen.Emit(OpCodes.Ret);
    
        Delegate emitted = dynamicMethod.CreateDelegate(
            typeof(Action<MyClass, string, string>));
        emitted.DynamicInvoke(this, "Hello", "World");
    }
    

    Replace “MyClass” with the name of your class.

    Regarding the EDIT of your question, you don’t need to generate a dynamic method by writing IL code in order to call a method dynamically at runtime. Just use Reflection, for example:

    public void DoSomething(object a, object b)
    {
        var method = GetType().GetMethod("DoSomethingElse", BindingFlags.Instance | BindingFlags.Public);
        method.Invoke(this, new object[] { a, b });
    }
    

    or:

    // Note “static”
    public static void DoSomething(dynamic instance, object a, object b)
    {
        // This will call whatever “DoSomethingElse” method exists on the type
        // that “instance” has *at run-time*
        instance.DoSomethingElse(a, b);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
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 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
Seemingly simple, but I cannot find anything relevant on the web. What is the
Does anyone know how can I replace this 2 symbol below from the string
this is what i have right now Drawing an RSS feed into the php,
I have just tried to save a simple *.rtf file with some websites and
I am trying to loop through a bunch of documents I have to put

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.