tags:

views:

117

answers:

4

We can call callback methods using delegates. For eg,

public delegate bool ContinueProcessing();

// later in code we can write ,

ContinueProcessing cp = new ContinueProcessing(IsDataAvailable);

cp += new ContinueProcessing(IsTransactionComplete);

//later in code defination of methods

bool IsDataAvailable() { return true; }

bool IsTransactionComplete() { return true; }

cp.Invoke() ;

The above call will call two boolean method one after the other. Why we need "Events" ? What is the purpose of "Events" ?

+10  A: 

Events are callbacks where you can have multiple subscribers who don't interfere with each other and can't call each other.

Delegates provide the encapsulation of "this is the action I want to take" and events provide the encapsulation of the pub/sub model.

See my article on events for more information.

Jon Skeet
thanks it's helpful
Ashish
A: 

Events are like when you see that there is a need to notify certain componets in your application.

Say there is a football match so you design your classes like

1- Players 2- Football and more like so each of the player objects are intrested in the location of the football

so to achive this functionality , you can use events where Football class will raise even and passing it's location and palyers will be notified about the new location.

this can also be achived by using Observer Pattern but Eventing is more helpful and leser code is required.

saurabh
I understand Saurabh. This is easiest way of calling callback methods.We can raise events and whovever subscribe will get invoked. We can do the same using only delegate and no events. my question was why events?
Ashish
A: 

Delegates are very generic. They can be used in any context: within the same class, between classes, in static methods etc.

Events are more specific -- they are specifically designed to be used for one class to subscribe to an event raised by another class.

Delegate is a (kind of) type-safe pointer to a function, whereas event is wrapper around delegate that provides standard interface to Subscribe/Unsubscribe/Raise an event.

zvolkov
Events only add "Add" and "Remove" methods around delegate. We can achieve everything without mentioning "Events". Why you say Delegates are more generic?
Ashish
Delegates are more generic in the sense that they can be used in a wider selection of scenarios. You can do many things with delegates, including implementing events, but with events you can only do one thing: events.
zvolkov
A: 

Looks like 'event' keyword is a modifier for a delegate declaration that allows it to be included in an interface, constraints it invocation from within the class that declares it, provides it with a pair of customizable accessors (add and remove) and forces the signature of the delegate (when used within the .NET framework).

Ashish