I don’t understand why we need the event keyword while defining events, when we can do the same thing without using the event keyword, just by using delegates.
E.g.:
public delegate void CustomEventHandler(int a, string b);
public event CustomEventHandler customEvent;
customEvent += new CustomEventHandler(customEventHandler);
customEvent(1,"a"); // Raising the event
Here, if I remove the event keyword from the second line, then I can also raise the event by invoking the delegate.
Can anybody please tell me why this event keyword is needed?
Field-like events and public fields of delegate types look similar, but are actually very different.
An event is fundamentally like a property – it’s a pair of add/remove methods (instead of the get/set of a property). When you declare a field-like event (i.e. one where you don’t specify the add/remove bits yourself) a public event is created, and a private backing field. This lets you raise the event privately, but allow public subscription. With a public delegate field, anyone can remove other people’s event handlers, raise the event themselves, etc – it’s an encapsulation disaster.
For more on events (and delegates) read my article on this topic. (At some point I need to update this for C# 4, which changes field-like events very slightly. The gist of it is still correct though.)