Skip to content

Instantly share code, notes, and snippets.

@sangheestyle
Created November 16, 2018 13:06
Show Gist options
  • Select an option

  • Save sangheestyle/b1b5cfb427bc2e817fa539cbde9e15e8 to your computer and use it in GitHub Desktop.

Select an option

Save sangheestyle/b1b5cfb427bc2e817fa539cbde9e15e8 to your computer and use it in GitHub Desktop.
C# event practice
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Counter c = new Counter(new Random().Next(10));
c.ThresholdReached += c_ThresholdReached;
Console.WriteLine("press 'a' key to increase total");
while (Console.ReadKey(true).KeyChar == 'a')
{
Console.WriteLine("adding one");
c.Add(1);
}
}
static void c_ThresholdReached(object sender, EventArgs e)
{
Console.WriteLine("The threshold was reached.");
Environment.Exit(0);
}
}
class Counter
{
private int threshold;
private int total;
public Counter(int passedThreshold)
{
threshold = passedThreshold;
}
public void Add(int x)
{
total += x;
if (total >= threshold)
{
OnThresholdReached(EventArgs.Empty);
}
}
protected virtual void OnThresholdReached(EventArgs e)
{
EventHandler handler = ThresholdReached;
if (handler != null)
{
handler(this, e);
}
}
public event EventHandler ThresholdReached;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment