Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are delegates in C# better than function pointers in C/C++?

Tags:

c

c#

.net

The delegates in C# offer similar functionality as function pointers in C. I heard someone saying "C# delegates are actually better than function pointers in C". How come? Please explain with an example.

like image 227
pecker Avatar asked Mar 29 '10 02:03

pecker


People also ask

How delegates are used in C#?

A delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. Delegates in C# are similar to the function pointer in C/C++. It provides a way which tells which method is to be called when an event is triggered.

What is delegate example?

Verb A manager should delegate authority to the best employees. Those chores can be delegated to someone else. He doesn't delegate very well.

What is delegates and its types?

A delegate(known as function pointer in C/C++) is a references type that invokes single/multiple method(s) through the delegate instance. It holds a reference of the methods. Delegate types are sealed and immutable type.

Are delegates static?

Represents a delegate, which is a data structure that refers to a static method or to a class instance and an instance method of that class.


2 Answers

"Better" is subjective -- but the main differences are:

  • Type safety. A delegate is not only guaranteed to refer to a valid method, it is guaranteed to refer to a method with the correct signature.
  • It's a bound method pointer -- that is, the delegate can point to a specific object on which to call the delegate. Thus, an Action<string> delegate could refer to alice.GetName or bob.GetName rather than just Person.GetName. This might be similar to C++ "pointer to member" -- I'm not sure.

In addition, the C# language supports closures through delegates to anonymous methods and lambda expressions -- i.e. capturing local variables of the declaring procedure, which delegate can reference when it later gets executed. This isn't strictly speaking a feature of delegates -- it's enabled by the C# compiler doing some magic on anonymous methods and lambda expressions -- but it's still worth mentioning because it enables a lot of the functional idioms in C#.

EDIT: As CWF notes in comments, another possible advantage of C# delegates is that the delegate type declarations are easier for many people to read. This may be a matter of familiarity and experience, of course.

like image 64
itowlson Avatar answered Oct 10 '22 12:10

itowlson


Pointers can always point to the wrong place :) I.e it can point to a non-function or an arbitrary place in memory.

But in terms of functionality, function pointers can do anything that delegates can do.

like image 42
Larry Watanabe Avatar answered Oct 10 '22 13:10

Larry Watanabe