Practical Example: Temperature Alert
Explore how to build a temperature monitoring program in C# by applying delegates and events. Learn to define custom event arguments, raise events in a publisher, and handle alerts with lambda expressions to create a flexible, decoupled system.
We'll cover the following...
We have explored how delegates and events allow us to treat behavior as data. Instead of hardcoding what a system should do when an action occurs, we can pass blocks of logic around our application dynamically.
To solidify these concepts, we'll build a complete temperature monitoring program from scratch. Our goal is to create a Thermostat that triggers an alert whenever the temperature exceeds a safe threshold. We will use the standard EventHandler<T> pattern, custom event arguments, and lambda expressions to handle the notifications.
Step 1: Define custom event arguments
Standard .NET conventions dictate that we create a class to hold the data sent to subscribers. ...