I am a little confuzed with events.
To use them first you define a delegate signature. Like:
Code:
public delegate void ButtonEventHandler();
Then we make a delegate (event) in our class. Like:
Code:
class TestButton
{
public event ButtonEventHandler OnClick;
// A method that triggers the event:
public void Click()
{
OnClick();
}
}
The class has a method or methods that trigger the event. The event is just a delegate that Click() invokes.
For handling events we subscribe handlers to events. That is exactly adding more methods to a delegate (Except when accessors are used). Like:
Code:
TestButton mb = new TestButton();
// Specify the method that will be triggered by the OnClick event.
mb.OnClick += new ButtonEventHandler(TestHandler);
// Specify an additional anonymous method.
mb.OnClick += delegate { System.Console.WriteLine("Hello, World!"); };
And event will be triggered by calling Click() method. Like:
Code:
// Trigger the event
mb.Click();
Everything is going fine. By raising the event, Click() method invokes OnClick event and because it is like a delegate it calls subscribed methods that are actually event handlers.
Now my question is: What is the difference between a delegate and an event? A delegate has the same functionality of an event. What will happen if we don't write event keyword in the class?