I don\'t understand why do we need the \"event\" keyword while defining events, when we can do the same thing without using \"event\" keyword, just by using the delegates.>
It's partly needed because if you omit the event
keyword, it breaks encapsulation. If it's just a public multicast delegate, anyone can invoke it, set it to null or tamper with it. If a class called MailNotifier
exists and it has an event called MailReceived
, it makes no sense for other types to be able to fire that event via calling mailNotifier.MailReceived()
;
On the other hand, you can only meddle with and invoke 'field like' events from the type that defined it.
If you wanted to keep your event invocation private, there's nothing to stop you doing something like this:
public class MyClassWithNonFieldLikeEvent
{
private CustomEventHandler m_delegate;
public void Subscribe(CustomEventHandler handler)
{
m_delegate += handler;
}
public void Unsubscribe(CustomEventHandler handler)
{
m_delegate -= handler;
}
private void DoSomethingThatRaisesEvent()
{
m_delegate.Invoke(...);
}
}
... but that's a whole load of code just to (more or less) do what field-like events already give us.