• 4

After reading the article- When to Use Delegates Instead of Interfaces (C# Programming Guide), I need some help understanding the below given points, which I found to be not so clear (for me). Any examples or detailed explanations available for these?

Use a delegate when:

  • An eventing design pattern is used.
  • It is desirable to encapsulate a static method.
  • Easy composition is desired.
  • A class may need more than one implementation of the method.

Use an interface when:

  • There are a group of related methods that may be called.
  • A class only needs one implementation of the method.

My Questions are,

  1. What do they mean by an eventing design pattern?
  2. How the composition turns out to be easy if a delegate is used?
  3. if there is a group of related methods that may be called,then use interface-What benefit it has?
  4. if a class only needs one implementation of the method, use interface-how is it justified in terms of benefits?

If my memory of .NET still holds, a delegate is basically a function ptr or functor. It adds a layer of indirection to a function call so that functions can be substituted without the calling code having to change. This is the same thing an interface does, except that an interface packages multiple functions together, and an implementor has to implement them together.

An event pattern, broadly speaking, is one where something responds to events from elswhere (such as Windows messages). The set of events is usually open ended, they can come in any order, and are not necessarily related to each other. Delegates work well for this in that each event can call a single function without needing a reference to a series of implementing objects that might also contain numerous irrelevant functions. In addition (this is where my .NET memory is vague), I think multiple delegates can be attached to an event.

Compositing, though I am not very familiar with the term, is basically designing one object to have multiple sub-parts, or aggregated children to which the work is passed down. Delegates allow the children to be mixed and matched in a more ad-hoc way where an interface might be overkill or cause too much coupling and the rigidity and fragility that comes with it.

The benefit to an interface for related methods is that the methods can share the state of the implementing object. Delegate functions cannot so cleanly share, or even contain, state.

If a class needs a single implementation, an interface is more suitable since within any class implementing the whole collection, only one implementation can be done, and you get the benefits of an implementing class (state, encapsulation. etc). If the implementation might change due to runtime state, delegates work better because they can be swapped out for other implementations without effecting the other methods. For instance, if there are three delegates that each have two possible implementations, you would need eight different classes implementing the three-method interface to account for all the possible combinations of states.

  • 0
Reply Report

1) Eventing patterns, well the classic is the Observer pattern, here's a good Microsoft link Microsoft talk Observer

The article you linked to isn't very well written imo and makes things more complicated than necessary. The static business is common sense, you can't define an interface with static members, so if you want polymorphic behaviour on a static method you would use a delegate.

The link above talks about delegates and why there are good for composition, so that might help with your query.

  • 1
Reply Report

What do they mean by an eventing design pattern?

They most likely refer to an implementation of the observer pattern which is a core language construct in C#, exposed as 'events'. Listening to events is possible by hooking a delegate to them. As Yam Marcovic pointed out, EventHandler is the conventional base delegate type for events, but any delegate type can be used.

How the composition turns out to be easy if a delegate is used?

This probably just refers to the flexibility delegates offer. You can easily 'compose' certain behavior. With the help of lambdas, the syntax to do this is also very concise. Consider the following example.

class Bunny
    Func<bool> _canHop;

    public Bunny( Func<bool> canHop )
        _canHop = canHop;

    public void Hop()
        if ( _canHop() )  Console.WriteLine( "Hop!" );

Bunny captiveBunny = new Bunny( () => IsBunnyReleased );
Bunny lazyBunny = new Bunny( () => !IsLazyDay );
Bunny captiveLazyBunny = new Bunny( () => IsBunnyReleased && !IsLazyDay );

Doing something similar with interfaces would require you to either use the strategy pattern or using an (abstract) base Bunny class from which you extend more specific bunnies.

if there is a group of related methods that may be called, then use interface-What benefit it has?

Again, I'll use bunnies to demonstrate how it would be easier.

interface IAnimal
    void Jump();
    void Eat();
    void Poo();

class Bunny : IAnimal { ... }
class Chick : IAnimal { ... }

// Using the interface.
IAnimal bunny = new Bunny();
bunny.Jump();  bunny.Eat();  bunny.Poo();
IAnimal chick = new Chick();
chick.Jump();  chick.Eat();  chick.Poo();

// Without the interface.
Action bunnyJump = () => bunny.Jump();
Action bunnyEat = () => bunny.Eat();
Action bunnyPoo = () => bunny.Poo();
bunnyJump(); bunnyEat(); bunnyPoo();
Action chickJump = () => chick.Jump();
Action chickEat = () => chick.Eat();

if a class only needs one implementation of the method, use interface-how is it justified in terms of benefits?

For this, consider the first example with the bunny again. If only one implementation is ever needed - no custom composition is ever required -, you can expose this behavior as an interface. You will never have to construct the lambdas, you can just use the interface.


Delegates offer a lot more flexibility, while interfaces help you establish strong contracts. Therefore I find the last point mentioned, "A class may need more than one implementation of the method.", by far the most relevant one.

An additional reason when to use delegates is when you want to expose only part of a class which you can't adjust the source file from.

As an example of such a scenario (maximum flexibility, no need to modify sources), consider this implementation of the binary search algorithm for any possible collection by just passing two delegates.

  • 3
Reply Report