Possible Duplicate:
What is the difference between a delegate and events?
This question I got at an interview and I still don't know what the answer should be.
I would appreciate any thoughts!
Delegate is a function pointer. It holds the reference of one or more methods at runtime. Delegate is independent and not dependent on events. An event is dependent on a delegate and cannot be created without delegates.
Event is a notification raised by an object to signal the occurrence of an action. Delegate is associated with the event to hold a reference of a method to be called when the event is raised.
A delegate is a person who is chosen to vote or make decisions on behalf of a group of other people, especially at a conference or a meeting.
Yes, you can declare an event without declaring a delegate by using Action. Action is in the System namespace.
I have an article on pretty much exactly
In brief, you can think of an event as being a bit like a property - but instead of having get/set operations, it has add/remove. The value being added/removed is always a delegate reference.
Delegates themselves support operations of:
Note that delegates themselves are immutable, so combine/remove operations return a new delegate instance rather than modifying the existing ones.
The other answers so far are all quite good. Here's another way to think about it.
What's the semantic difference between a property and a field? I don't mean what are the technical differences, like a property is actually a pair of methods, blah blah blah. I mean, as far as understanding the meaning of a program goes, what is the difference?
A property is usually a public member of a class, and it represents a property of the thing being modelled. That is, you want to make a model of a newspaper so you make a class Newspaper and you give it a property Publisher. The publisher is a property of newspapers, so Publisher is a property of the Newspaper class.
A field is usually an implementation detail of a class. Maybe the Publisher property is actually implemented as a field. But newspapers do not have "fields", so you don't expose the publisher field as a public member of the Newspaper class; you use it as a private implementation detail of the Publisher property.
Events and delegates are somewhat analogous. An event is something in the model. A button is a thing that can inform you when it is clicked, so the Button class has a "Click" event. The delegate that actually does the informing is the implementation detail of the event.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With