Delegates enforce type-safe calls to methods. This typically works by static type checking performed by the compiler. But is not the only way, you can use Delegate.DynamicInvoke()
to bypass compiler type checking. An example:
using System;
class Program {
delegate void foo(long arg);
static void Main(string[] args) {
var obj = new Example();
var dlg = Delegate.CreateDelegate(typeof(foo), obj, "Target");
dlg.DynamicInvoke(42);
}
}
class Example {
private long field;
public void Target(long arg) {
field = arg;
}
}
Now start tinkering with this code, the kind of things you can do to try to fool the type system:
- change the foo delegate declaration
- pass a different delegate type as the 1st argument
- pass an object of a different class as the 2nd argument
- change the target method name
- pass an argument of a different type in the
DynamicInvoke
call
- pass a different set of arguments in the
DynamicInvoke
call
All of these attempts will compile without complaint. None of them will execute, you'll get runtime exceptions. That's what makes delegates secure, you cannot use them to invoke a method that will leave the stack imbalanced or induce the target method to access stack locations that are not initialized or not part of the activation frame. The traditional way malware hijacks code. No such runtime checking exists in C or C++, their compilers performs static checking only and that can be bypassed with a simple cast.