Editorials

Sometimes a Delegate Is Enough

The decision to use a Delegate over inheritance is pretty straight forward in my simple understanding. Inheritance is best when you have a number of methods or properties that must follow a specific contract, ie. an interface. When all you want to do is to dynamically determine what method to call, which may have a different internal behavior, but share the same input and output parameters, then a delegate may be the better option. With lambda expressions, it is even easier to have different implementations for a delegate.

For example, consider you have a collection containing a list of key value pairs of name and value. If you wanted to format the contents of that collection in different ways you could easily use a delegate to determine which method to call.

Clearly, you could put the decision to select the desired method in the middle of your loop while traversing the collection. The problem is that you execute the if statement as many times as the count of your collection content.

Using a delegate, you can create a delegate variable and assign it to the desired method prior to processing the loop. Then for each iteration in the loop simply call the delegate variable. In this fashion the selection of the method is only determined one time outside your loop.

If you had a number of methods needing execution for each item in the collection, then an interface with different implementations probably is a better choice at this point. I suppose you could use multiple delegates. But if there is state that needs to be maintained between method calls a class is a lot easier to implement.

For many of our readers this is second nature. Still, I’m surprised how often I start creating interfaces and class implementations when a simple delegate will serve. Don’t forget you can use a delegate much as you could use a function pointer in C++. It can save you a lot of time and improve the performance of your program.

While this is a beginner topic it can be a good reminder for us all. Why not share your ideas of "No Brainer" choices that are easy to forget? Add your thoughts to the conversation here or by email to btaylor@sswug.org.

Cheers,

Ben