Saturday, March 03, 2007

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:
  1. An interface provides a level of indirection/abstraction for a class - a delegate provides a level of indirection/abstraction for a function
  2. An interface provides signatures for a bunch of functions/properties - a delegate provides signatures for a function
  3. both can be passed as variables
  4. An interface will only work with an object, whereas a delegate can work with static and instance methods
  5. Finally, delegates can be "invoked" or called asynchronously
  6. An interface quite clearly relates to a class
  7. 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!


At 1:16 pm, Blogger Jim said...

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?

At 7:50 pm, Blogger MAG said...

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