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');
}
}
}