views:

4358

answers:

8

I don't see advantages of using events over delegates, other than being syntactical sugar . Perhaps I am misunderstanding, but it seems that events is just a placeholder for delegate.

Would you guys explain to me the differences and when to use which? what are the advantages and disadvantages? Our code is heavily rooted with events, and I want to get to the bottom of it.

Thanks

Edit#1

When would you use delegates over events and vs.versa? Please state your real world experience with both, say in the production code.

Edit#2

Guys let's talk more about when you would use one over the other and visa versa. At the end of the day, I will sum up the differences.

+13  A: 

I found this page very helpful in understanding the difference.

http://blog.monstuff.com/archives/000040.html

Jonathon Watney
I will take a look. thx. I have further questions in edited post.
+1 for that article. To sum up the main points of the article: 1. The "event" keyword allows for a delegate declaration in an interface. 2. Constrains the invocation to only the class that declared it. 3. Adds "get/set" accessors (actually called add/remove). 4. Forces the method signature to conform to "MyEvent(object source, EventArgs e)".
Repo Man
A: 

Events is Delegates that have more security.
Only the holding class can fire the event.
All other classes (include the derived from holding class) is can use only use the (+=, -=) syntax.


Update:
In class system i use Events
In the true, i am use delegate only in reflection code.

Avram
If Jon Skeet saw this "Events is Delegates that have more security.", he would have viciously attacked you...One thing are can say with confidence -- they are NOT the same thing
A: 

Events are syntactical sugar. They are delicious. When I see an event, I know what to do. When I see a delegate, I'm not so sure.

Combining events with interfaces (more sugar) makes for a mouth watering snack. Delegates and pure virtual abstract classes are much less appetizing.

Sean
that's how I see it too. I want deeper and more sweet explanation :)
Too much sugar makes one fat, however... =P
Erik Forbes
+1  A: 

Events are marked as such in the metadata. This allows things like the Windows Forms or ASP.NET designers to distinguish events from mere properties of delegate type, and provide appropriate support for them (specifically showing them on the Events tab of the Properties window).

Another difference from a property of delegate type is that users can only add and remove event handlers, whereas with a property of delegate type they can set the value:

someObj.SomeCallback = MyCallback;  // okay, replaces any existing callback
someObj.SomeEvent = MyHandler;  // not okay, must use += instead

This helps to isolate event subscribers: I can add my handler to an event, and you can add your handler to the same event, and you won't accidentally overwrite my handler.

itowlson
+8  A: 

From the technical standpoint, other answers have addressed the differences.

From a semantics perspective, events are actions raised by an object when certain conditions are met. For example, my Stock class has a property called Limit, and it raises an event when the stock prices reaches the Limit. This notification is done via an event. Whether anyone actually cares about this event and subscribes to it is beyond the concern of the owner class.

A delegate is a more generic term to describe a construct similar to a pointer in C/C++ terms. All delegates in .Net are multicast delegates. From a semantics perspective, they are generally used as a kind of input. In particular, they are a perfect way to implement the Strategy Pattern. For example, if I want to sort a List of objects, I can provide a Comparator strategy to the method to tell the implementation how to compare two objects.

I have used the two methods in production code. Tons of my data objects notify when certain properties are met. Most basic example, whenever a property changes, a PropertyChanged event is raised (see INotifyPropertyChanged interface). I have used delegates in code to provide different strategies of turning certain objects into string. This particular example was a glorified ToString() list of implementations for a particular object type to display it to users.

siz
Maybe I'm missing something, but isn't an Event Handler a type of delegate?
R. Bemrose
My answer addresses the questions Edit #1 and #2; differences from a usage perspective. For the purposes of this discussion, they are different, even though, from a technical standpoint, you are correct. Take a look at the other answers for technical differences.
siz
"All delegates in .Net are multicast delegates"? Even delegates that return values?
Qwertie
Yes. For history, take a look at http://msdn.microsoft.com/en-us/magazine/cc301816.aspx. Check out: http://msdn.microsoft.com/en-us/library/system.delegate.aspx. If they return values, the value that is returned is the evalutation of last delegate in the chain.
siz
+6  A: 

The keyword event is a scope modifier for multicast delegates. Practical differences between this and just declaring a multicast delegate are as follows:

  • You can use event in an interface.
  • Invocation access to the multicast delegate is limited to the declaring class. The behaviour is as though the delegate were private for invocation. For the purposes of assignment, access is as specified by an explicit access modifier (eg public event).

As a matter of interest, you can apply + and - to multicast delegates, and this is the basis of the += and -= syntax for the combination assignment of delegates to events. These three snippets are equivalent:

B = new EventHandler(this.MethodB);
C = new EventHandler(this.MethodC);
A = B + C;

Sample two, illustrating both direct assignment and combination assignment.

B = new EventHandler(this.MethodB);
C = new EventHandler(this.MethodC);
A = B;
A += C;

Sample three: more familiar syntax. You are probably acquainted with the assignment of null to remove all handlers.

B = new EventHandler(this.MethodB);
C = new EventHandler(this.MethodC);
A = null;
A += B;
A += C;
Peter Wone
+ for "Invocation access to the multicast delegate is limited to the declaring class"- that to me is the key difference point between delegates and events.
RichardOD
Another important difference (mentioned by itowlson below) is that one can't unsubscribe all event handlers by assigning to an event, but they could do that with a delegate. (By the way, yours was the most useful answer to me of all these).
romkyns
A: 

Although I've got no technical reasons for it, I use events in UI style code, in other words, in the higher levels of the code, and use delegates for logic that lays deeper in the code. As I say you could use either, but I find this use pattern to be logically sound, if nothing else, it helps document the types of callbacks and their hierarchy too.


Edit: I think the difference in usage patterns I have would be that, I find it perfectly acceptable to ignore events, they are hooks/stubs, if you need to know about the event, listen to them, if you don't care about the event just ignore it. That's why I use them for UI, kindof Javascript/Browser event style. However when I have a delegate, I expect REALLY expect someone to handle the delegate's task, and throw an exception if not handled.

Robert Gould
Would you elaborate on that as I also make use of evens in UI? A good example would be suffice....thanks
+2  A: 

Edit#1 When would you use delegates over events and vs.versa? Please state your real world experience with both, say in the production code.

When I design my own APIs, I define delegates which are passed as parameters to methods, or to the constructors of classes:

  • So that a method can implement a simple 'template method' pattern (as e.g. the Predicate and Action delegates are passed to the .Net generic collection classes)
  • Or so that the class can do a 'callback' (typically a callback to a method of the class which created it).

These delegates are generally non-optional at run-time (i.e. mustn't be null).

I tend not to use events; but where I do use events, I use them for optionally signalling events to zero, one, or more clients that might be interested, i.e. when it makes sense that a class (e.g. the System.Windows.Form class) should exist and run whether or not any client has added an event handler to its event (e.g. the form's 'mouse down' event exists, but it's optional whether any external client is interested in installing an event handler onto that event).

ChrisW