From 2b07530bb32205b2886b04b8135d57674bae2cb8 Mon Sep 17 00:00:00 2001 From: Jason Zhu Date: Mon, 22 Feb 2021 11:25:40 +0000 Subject: [PATCH] Finished Defining an Event & Subscribing to an Event --- gradebook/src/GradeBook/Book.cs | 10 ++++++++++ gradebook/src/GradeBook/Program.cs | 11 +++++++++++ 2 files changed, 21 insertions(+) diff --git a/gradebook/src/GradeBook/Book.cs b/gradebook/src/GradeBook/Book.cs index ceafed4..d45358e 100644 --- a/gradebook/src/GradeBook/Book.cs +++ b/gradebook/src/GradeBook/Book.cs @@ -3,6 +3,8 @@ using System.Collections.Generic; namespace GradeBook { + public delegate void GradeAddedDelegate(object sender, EventArgs args); + public class Book { private List grades; @@ -27,6 +29,12 @@ namespace GradeBook if (grade <= 100 && grade >= 0) { this.grades.Add(grade); + + if (GradeAdded != null) + { + // Somebody is listening/subscribing + GradeAdded(this, new EventArgs()); // sender = this, pass; Raising event + } } else { throw new ArgumentException($"Invalid {nameof(grade)}"); @@ -52,6 +60,8 @@ namespace GradeBook } } + public event GradeAddedDelegate GradeAdded; + public Statistics GetStatistics() { var result = new Statistics(); diff --git a/gradebook/src/GradeBook/Program.cs b/gradebook/src/GradeBook/Program.cs index 45ab748..54de553 100644 --- a/gradebook/src/GradeBook/Program.cs +++ b/gradebook/src/GradeBook/Program.cs @@ -14,6 +14,11 @@ namespace GradeBook // book.AddGrade(87.2); var book = new Book("Jason's Grade Book"); + book.GradeAdded += OnGradeAdded; + book.GradeAdded += OnGradeAdded; + book.GradeAdded -= OnGradeAdded; + book.GradeAdded -= OnGradeAdded; + string input; while (true) @@ -54,5 +59,11 @@ namespace GradeBook Console.WriteLine($"The highesst grade is {stats.highGrade}"); Console.WriteLine($"The average grade is {stats.Average:N1}"); } + + static void OnGradeAdded(object sender, EventArgs e) + { + // Main is static, so it can only call static methods, hence return type is static + Console.WriteLine("A line has added"); + } } }