Search⌘ K
AI Features

Solution: Security System Alert

Understand the implementation of delegates and events in C# by examining a security system alert solution. Learn how to subscribe anonymous methods using lambda expressions, safely invoke events, and restrict external access with the event keyword to handle motion detection effectively.

We'll cover the following...
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);
}
}
...