Tuesday 9 May 2017

Events 01

Events are basically a communication from a provider class that invokes an eventhandler which allows subscribers of that event to know that something occurred, it's up to the subscribers to to something about it.

let's create an example to drive this home, below is a water tank class that has a capacity and current level properties, it also has an overflow event handler and a method to increase the current level

using System;

namespace pc.eventsExample01
{
    class WaterTank
    {
        public int MaxCapacity { get; private set; }
        public int CurrentLevel { get; private set; }
        public EventHandler Overflow { get; set; }
        public WaterTank(int MaxLiters)
        {
            this.MaxCapacity = MaxLiters;
        }
        public void IncreaseLevel(int Liters)
        {
            CurrentLevel += Liters;

            //if we go over the capacity there's an overflow
            if (CurrentLevel > MaxCapacity && Overflow != null)
                Overflow.Invoke(this, null);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            char selection;
            var wt = new WaterTank(50);

            //define and subscribe event
            wt.Overflow += (s, e) => Console.WriteLine("OVERFLOW!!!!");

            do
            {
                Console.WriteLine("\n1)Add to tank\n2)check current level\n0)exit");

                switch (selection = Console.ReadKey().KeyChar)
                {
                    case '1':
                        Console.WriteLine("\nhow many liters to add? ");
                        int l = 0;
                        int.TryParse(Console.ReadLine(), out l);
                        wt.IncreaseLevel(l);
                        break;
                    case '2':
                        Console.WriteLine($"\nWater Tank level {wt.CurrentLevel}");
                        break;
                    default:
                        Console.WriteLine("No such command");
                        break;
                }

            } while (selection != '0');
        }
    }
}


Notice that our water tank defines the overflow event and when it is invoked, but it's our main that actually handles it, that is it does something, in this case just prints "OVERFLOW!!!" to the screen.