Created
November 16, 2018 13:06
-
-
Save sangheestyle/b1b5cfb427bc2e817fa539cbde9e15e8 to your computer and use it in GitHub Desktop.
C# event practice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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