I was wondering if it was possible to dynamically inject a function parameter at runtime. For e.g. I have a class with two overloaded methods say
Class C1
{
public static void Func1(object o)
{
}
public static void Func1()
{
}
}
Class C2
{
public void Func1()
{
C1.Func1();
}
}
Now, is it possible to dynamically replace the call to Func1() with a call to the overloaded method C1.Func1(object o) passing in either ‘this’ or the type object as the parameter.
So, in affect when I call C1.Func1(), my code should call C1.Func1(this);
I am assuming that by “dynamic” you mean a post-compile time solution, but not necessarily at runtime. The latter would be more challenging but could be done. For the former it’s rather easy if you know some IL. I note that
C2.Func1compiles to something likewhich you can easily replace with
This is because argument zero in an instance method is always the
thisreference for the current instance and we can push it on the stack with the instructionldarg.0. Moreover, we simply replace the signature of the method that we are invoking from the parameterless method to the method accepting a singleobjectas a parameter.You can easily decompile to IL using
ildasmand recompile usingilasm.