-2

Could anyone please explain the difference between using action and events in c#?

Sonu Jose
  • 123
  • 2
  • 6
  • http://stackoverflow.com/questions/1431359/event-action-vs-event-eventhandler or http://stackoverflow.com/questions/2282476/actiont-vs-delegate-event or http://stackoverflow.com/questions/1750628/action-vs-event-action – Soner Gönül Nov 17 '15 at 12:14
  • You should read Jon Skeet's article labeled [Delegates and Events](http://csharpindepth.com/Articles/Chapter2/Events.aspx) – kkyr Nov 17 '15 at 12:14
  • 1
    In short, both are delegates, but `EventHandler` is designed specifically for handling events and `Action` is a more general purpose delegate for all other situations where no return type is needed. – David Arno Nov 17 '15 at 12:18

1 Answers1

1

In short: an Action is a single callback / delegate. An event is multicast callback / delegate. So while an Action can call only one handler an event can have multiple handlers.

Event-Sample:

// Subscribe
MyEvent += MyMethod1;
MyEvent += MyMethod2;

// Unsubscribe
MyEvent -= MyMethod1;
MyEvent -= MyMethod2;

If the event MyEvent gets raised/called both methods (MyMethod1 and MyMethod2) get called. You can not use += operator for actions.

Action-Sample:

MyAction = MyMethod3;

Actions are mainly used for some local callback mechanism. For example accept a parameter of Type Action<>. If an action should have a result one can use Func<> instead Action<>. Both are handy for a API that accepts Lambda's.

If a class expose some general "callback" they should be exposed as regular events.

Marc
  • 4,715
  • 3
  • 27
  • 34