Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

When should I use events and when delegates?

Status
Not open for further replies.

beginwithl

Programmer
Jan 11, 2009
2
SI
hi

I’m a bit confused about when I should implement events and when delegates.

BTW: I realize that event is only a modifier that gives controlled access to its privately declared delegate



1)
a) As far as I understand it, we should choose events over delegates when encapsulation is of importance and thus we want only for publisher class to be able to call subscribed methods?


b) But, while it is true that event can only be invoked from within the class that declares it, couldn’t the same level of encapsulation be achieved with a delegate object also, assuming we declare it as being private?




2) In any case, I still don’t know based on what criteria I should decide when I need the kind of encapsulation ( and thus safety ) the events offer, and when using the delegate objects would suffice?




3) Are delegates really all that useful by themselves, or do we most of the times use events? If so, why?




thank you
 
I'm not going to offer my thoughts about design concepts because honestly I'm not good on this subject. =)

Delegates are pretty useful. They are like the interfaces, just contracts, except they deal only with methods. (I cannot think of a good example now.) They are also useful for parameterized threading, though I don't think mentioning this fits with the topic.

Events are like list of delegates. You can mimic an event by using a generic list of a certain delegate. To trigger this "event", invoke each delegate item. If you need this kind of list, then just use events, easier to use.

In the OOP side of events, I suggest reading about the observer pattern.


just my 2cents
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top