Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegates in C# and fnc pointers in C++

Tags:

c#

delegates

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.

like image 767
smallB Avatar asked May 26 '12 12:05

smallB


1 Answers

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.

like image 108
Hans Passant Avatar answered Oct 13 '22 23:10

Hans Passant