As other people have said, delegates are convenient for callbacks. They are useful for the whole load of other things. For example, in a game in which I worked on recent bullets, different things are done when they fall (some cause damage, some actually increase the health of the person they hit, some do no damage, but poison the target, etc.) . The classic OOP way for this would be a bullet base class and loading subclasses
Bullet DamageBullet HealBullet PoisonBullet DoSomethingElseBullet PoisonAndThenHealBullet FooAndBarBullet ....
With this pattern, I have to define a new subclass every time I need some new behavior in the pool, which is a mess and leads to a lot of duplicate code. Instead, I solved it with delegates. The bullet has an OnHit delegate that gets called when the bullet hits the object, and of course I can make this delegate anything. So now I can create such bullets
new Bullet(DamageDelegate)
This is obviously a much better way to do something.
In functional languages, you tend to see much more of this kind of thing.
Martin Apr 20 '10 at 21:28 2010-04-20 21:28
source share