File tree Expand file tree Collapse file tree 3 files changed +76
-0
lines changed
DownloadableCodeProjects/LP6_implement-delegates-events/Events/Solution Expand file tree Collapse file tree 3 files changed +76
-0
lines changed Original file line number Diff line number Diff line change
1
+ public class Counter
2
+ {
3
+ public int Total { get ; private set ; }
4
+ public int Threshold { get ; set ; }
5
+
6
+ public Counter ( int threshold )
7
+ {
8
+ Threshold = threshold ;
9
+ Total = 0 ;
10
+ }
11
+
12
+ public void Add ( int value )
13
+ {
14
+ Total += value ;
15
+ Console . WriteLine ( $ "Current Total: { Total } ") ; // Debugging output
16
+ if ( Total >= Threshold )
17
+ {
18
+ var args = new ThresholdReachedEventArgs
19
+ {
20
+ Threshold = Threshold ,
21
+ TimeReached = DateTime . Now
22
+ } ;
23
+ OnThresholdReached ( args ) ;
24
+ }
25
+ }
26
+
27
+ public event EventHandler < ThresholdReachedEventArgs > ThresholdReached = delegate { } ;
28
+
29
+ protected virtual void OnThresholdReached ( ThresholdReachedEventArgs e )
30
+ {
31
+ ThresholdReached ? . Invoke ( this , e ) ;
32
+ }
33
+ }
34
+
35
+ public class ThresholdReachedEventArgs : EventArgs
36
+ {
37
+ public int Threshold { get ; set ; }
38
+ public DateTime TimeReached { get ; set ; }
39
+ }
Original file line number Diff line number Diff line change
1
+ <Project Sdk =" Microsoft.NET.Sdk" >
2
+
3
+ <PropertyGroup >
4
+ <OutputType >Exe</OutputType >
5
+ <TargetFramework >net9.0</TargetFramework >
6
+ <ImplicitUsings >enable</ImplicitUsings >
7
+ <Nullable >enable</Nullable >
8
+ </PropertyGroup >
9
+
10
+ </Project >
Original file line number Diff line number Diff line change
1
+ var counter = new Counter ( 10 ) ;
2
+
3
+ // Subscribe to the ThresholdReached event
4
+ counter . ThresholdReached += Counter_ThresholdReached ;
5
+
6
+ // Increment the counter interactively
7
+ Console . WriteLine ( "Press 'a' to add 1 to the counter or 'q' to quit." ) ;
8
+ while ( true )
9
+ {
10
+ var key = Console . ReadKey ( true ) . KeyChar ;
11
+ if ( key == 'a' )
12
+ {
13
+ counter . Add ( 1 ) ;
14
+ }
15
+ else if ( key == 'q' )
16
+ {
17
+ break ;
18
+ }
19
+ }
20
+
21
+ // Unsubscribe from the ThresholdReached event
22
+ counter . ThresholdReached -= Counter_ThresholdReached ;
23
+
24
+ static void Counter_ThresholdReached ( object ? sender , ThresholdReachedEventArgs e )
25
+ {
26
+ Console . WriteLine ( $ "Threshold of { e . Threshold } reached at { e . TimeReached } .") ;
27
+ }
You can’t perform that action at this time.
0 commit comments