Solution: Security System Alert

Review how to protect delegates with the event keyword and handle subscriptions.

Solution: Security System Alert

Review how to protect delegates with the event keyword and handle subscriptions.
C# 14.0
var securityHub = new SecuritySystem();
securityHub.SensorTripped += zone => Console.WriteLine($"Turning on floodlights for {zone}...");
securityHub.SensorTripped += zone => Console.WriteLine($"Sounding main alarm for {zone}...");
Console.WriteLine("System Armed.");
securityHub.DetectMotion("Backyard");
securityHub.DetectMotion("Garage");
// --- Class Definitions ---
public delegate void SensorTrippedHandler(string zone);
public class SecuritySystem
{
public event SensorTrippedHandler? SensorTripped;
public void DetectMotion(string zone)
{
Console.WriteLine($"\n> Motion detected in zone: {zone}");
SensorTripped?.Invoke(zone);
}
}