c# - What does the statement "delegates are secure" mean? -


in c# documentation delegates, says "a delegate reference type can used encapsulate named or anonymous method. delegates similar function pointers in c++; however, delegates type-safe , secure"

my question is, mean delegate "secure"?

delegates enforce type-safe calls methods. typically works static type checking performed compiler. not way, can use delegate.dynamicinvoke() bypass compiler type checking. 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 code, kind of things can try fool type system:

  • change foo delegate declaration
  • pass different delegate type 1st argument
  • pass object of different class 2nd argument
  • change target method name
  • pass argument of different type in dynamicinvoke call
  • pass different set of arguments in dynamicinvoke call

all of these attempts compile without complaint. none of them execute, you'll runtime exceptions. that's makes delegates secure, cannot use them invoke method leave stack imbalanced or induce target method access stack locations not initialized or not part of activation frame. traditional way malware hijacks code. no such runtime checking exists in c or c++, compilers performs static checking , can bypassed simple cast.


Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -