Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event, delegate or interface? [closed]

Tags:

c#

Suppose I have a Monkey class which sometimes needs to acquire an instance of Banana. The way this banana is provided is not of interest to the monkey, but it does initiate the banana acquisition.

Now I have at least three possible ways to wire my monkey to a banana provider. What is the best way to do it?

1. Event

Raise a Monkey.BananaNeeded event. The event handler sets the BananaNeededEventArgs.Banana property.

2. Interface

Invoke IBananaProvider.GetBanana. The IBananaProvider instance is injected in the monkey as a constructor argument or through a property.

3. Delegate

Invoke a delegate of type System.Func<Banana>. The delegate is injected in the monkey as a constructor argument or through a property. This one is tempting because it doesn't require the declaration of any extra interfaces or classes, but apparently it is not a popular choice.

like image 439
Wim Coenen Avatar asked Sep 10 '25 21:09

Wim Coenen


1 Answers

I don't like the event and delegate options unless there is a mechanism to ensure multiple handlers won't be attached. Option 2 is therefore the winner, IMO.

like image 73
Michael A. McCloskey Avatar answered Sep 12 '25 10:09

Michael A. McCloskey