5

I'm trying to familiarize myself with delegates and on http://msdn.microsoft.com/en-us/library/aa288459(v=vs.71).aspx, I'm reading:

"Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and secure."

a mean, I do have C++ background, and somewhat cannot see how to understand the word "unlike" there. What do they mean by delegates are object-oriented and C++ fnc pointers are not? Same for type safe, and secure.

Anyone could show few examples and contra-examples?

Thanks.

smallB
  • 16,662
  • 33
  • 107
  • 151
  • 1
    See this questions.....[Type Unsafe of c++ function pointers][1] [Why c# function pointer is better than c++ function pointer][2] [1]: http://stackoverflow.com/questions/10237847/how-are-function-pointers-type-unsafe [2]: http://stackoverflow.com/questions/2535516/how-are-delegates-in-c-sharp-better-than-function-pointers-in-c-c – Md Kamruzzaman Sarker May 26 '12 at 12:37
  • Possible Duplicate:[are there function pointers in C#](http://stackoverflow.com/questions/2738850/are-there-function-pointers-in-c) – Kirin Yao May 26 '12 at 12:43
  • #MdKamruzzamanPallob from first link: "Function pointers are in fact type checked and are type safe." – smallB May 26 '12 at 12:57
  • #MdKamruzzamanPallob After reading those two links, my conclusion is: delegates are in no way more safe, more type-safe nor more object oriented. Again, example of "management talk" from MS. Thanks for providing those links. – smallB May 26 '12 at 13:01
  • 2
    The problem with C++ function pointers is how to bind the first parameter to a fixed value in a well defined way. – CodesInChaos May 26 '12 at 13:44

1 Answers1

6

A delegate does quite a bit more than a function pointer. It not only stores the function address, it also stores a reference to the target object. Unlike a C++ method pointer. So it is simple to use to call an instance method. That takes care of the "object-oriented" claim.

A bit down-hill from there, but type safety is ensured by the compiler verifying that the function signature exactly matches the delegate type when you assign the delegate. Which is no different in C++ but there's no way to cast a mismatch away. Another possible security aspect is that the object reference held by the delegate object is visible to the garbage collector. So you can never call an instance method on a deleted object.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536