delegates and interfaces
In trying to explain some functional concepts in C# to an OO programmer, it became apparent that there is a quite clear correspondance between an interface and a delegate (function pointer).
The following is a list of comparisons:
- An interface provides a level of indirection/abstraction for a class - a delegate provides a level of indirection/abstraction for a function
- An interface provides signatures for a bunch of functions/properties - a delegate provides signatures for a function
- both can be passed as variables
- An interface will only work with an object, whereas a delegate can work with static and instance methods
- Finally, delegates can be "invoked" or called asynchronously
- An interface quite clearly relates to a class
- An class can only implement an interface once, but can have many functions, which match a delegate
In many cases a delegate can provide simpler implementation than an interface, especially when the function is stateless and can therefore be made static therefore reducing side-effects. Its food for thought anyway!
2 Comments:
Mark, on a similar theme, the Java community are currently considering whether and how to add closures to Java 7. For an interesting entry point, try Elliott Harold's blog here and work backwards.
Can delegates in C# carry data with them?
Yup, I'm using them all the time. C# 3.0 takes it even further with functional syntax, anonymous classes, lambda expressions, extension methods - basically the Microsoft guys have gone mad for functional programming and the f# language, based on OCaml is really leading the way.
I am going to write an article one what goes on under the hood as it ends up compiling into good old classes to store the data.
Post a Comment
<< Home