Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the statement "delegates are secure" mean?

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"?

like image 1000
Terry Price Avatar asked Jul 07 '12 14:07

Terry Price


People also ask

Why delegates are type-safe?

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.

What do you mean by delegates with example?

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.

Can delegates be shared?

Delegates can be shared.

Can a delegate be private?

Just like classes and interfaces, we can declare delegates outside of classes or nested within classes. We can mark them private , public , or internal .


1 Answers

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.

like image 107
Hans Passant Avatar answered Oct 23 '22 06:10

Hans Passant