Practical Example: Temperature Alert
Apply delegates, events, and lambdas to build a real-world temperature monitoring and alert 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. This class must inherit from System.EventArgs. We need to send the current temperature and the defined threshold to any system listening for an alert.