In the C# documentation for delegates, it says "A delegate is a reference type that can be used to encapsulate a named or an anonymous method. Delegates are similar to function pointers in C++; however, delegates are type-safe and secure"
My question is, what do they mean by a delegate it "secure"?
A delegate is a type-safe function pointer that can reference a method that has the same signature as that of the delegate. You can take advantage of delegates in C# to implement events and call-back methods. A multicast delegate is one that can point to one or more methods that have identical signatures.
Delegates allow methods to be passed as parameters. Delegates can be used to define callback methods. Delegates can be chained together; for example, multiple methods can be called on a single event. Methods don't have to match the delegate type exactly.
Delegates can be shared.
Just like classes and interfaces, we can declare delegates outside of classes or nested within classes. We can mark them private , public , or internal .
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:
DynamicInvoke
callDynamicInvoke
callAll 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With