views:

739

answers:

4

What is the difference between a delegate and an event? Don't both hold references to functions to be executed?

A: 

Events: you can have more than one (and they can pile up if you forget to -= them, causing hard to find bugs). Chaining delegates would have to be done manually.

Jared Updike
Not true: http://msdn.microsoft.com/en-us/library/ms173175(VS.80).aspx
recursive
Wow it's unfortunate that they call it composing when functional composition is not the same thing (b would be passed a)... but it's cool that delegates can be easily chained. Thanks for the link.
Jared Updike
+17  A: 

An Event declaration adds a layer of abstraction and protection on the delegate instance. This protection prevents clients of the delegate from resetting the delegate and its invocation list and only allows adding or removing targets from the invocation list.

Simucal
+7  A: 

In addition to the syntactic and operational properties, there's also a semantical difference.

Delegates are, conceptually, function templates; that is, they express a contract a function must adhere to in order to be considered of the "type" of the delegate.

Events represent ... well, events. They are intended to alert someone when something happens and yes, they adhere to a delegate definition but they're not the same thing.

Even if they were exactly the same thing (syntactically and in the IL code) there will still remain the semantical difference. In general I prefer to have two different names for two different concepts, even if they are implemented in the same way (which doesn't mean I like to have the same code twice).

Jorge Córdoba
Excellent description of Delegates.
Jonathan Sampson
+1  A: 

You can also use events in interface declarations, not so for delegates.

Paul Hill