Search code examples
c#c#-4.0dynamiccil

Can I emit CIL inside an existing method?


I need to change some basic calculations during the life-time of an object.

I know how to create a dynamic method and call it through delegate.Invoke; however it is twice as costly as a static method call.

Is it possible to emit CIL inside an existing method?

Say one method calls another and the another can have different body (one at a time):

public void Worker()
{
    while(true)
    {
        int a = queueA.Dequeue();
        int b = queueB.Dequeue();

        int c = Calculate(a,b);
    }
}

int Calculate(int a, int b)
{
    // here goes dynamic code.
    // could be return a - b;
    // could be return b - a;
}

Please note that the calculation logic in the example is greatly simplified.


Solution

  • Once a class is compiled you can no longer change its IL. You can emit entire new methods dynamically at runtime using Reflection.Emit. But you cannot modify existing ones.

    If you need the speed of static method calls you might consider different approaches that OOP offer for example.