Events in C#

Events in C# are used by objects to signal an occurrence of an action.

To understand events, we need to introduce delegates first.

public delegate void TurnedOnEventHandler(Object sender, EventArgs e);
Delegates are used to reference a given method. The TurnedOnEventHandler delegate will point to a method which returns void and takes in two parameters: Object sender and EventArgs e.

Below you can see the definition of VendingMachine class which contains an event CapacityReachedEvent initialized through the constructor. The class also has a TurnOn method used to fire the event.

using System;

public delegate void TurnedOnEventHandler(Object sender, EventArgs e);

public class VendingMachine
{
    public event TurnedOnEventHandler CapacityReachedEvent;

    public VendingMachine(TurnedOnEventHandler handler)
    {
        CapacityReachedEvent = handler;
    }

    public void TurnOn()
    {
        CapacityReachedEvent(this, null);
    }
}
Note: The CapacityReachedEvent was incorrectly named in the video, it should be TurnedOnEvent.

Now, we can use the Main method to create an instance of VendingMachine using the TurnedOnEventHandler instantiated with the delegate pointing to the Handler method.


public class Program
{
    public static void Main()
    {
        var vendingMachine = new VendingMachine(new TurnedOnEventHandler(Handler));
        vendingMachine.TurnOn();
    }

    private static void Handler(Object sender, EventArgs e)
    {
        Console.WriteLine("The vending machine has been turned on!");
    }
}
Result:

The vending machine has been turned on!