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.
The delegates in C# offer similar functionality as function pointers in C. I heard
Share
“Better” is subjective — but the main differences are:
Action<string>delegate could refer toalice.GetNameorbob.GetNamerather than justPerson.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.