Exercise: Security System Alert
Problem statement
You are developing software for a smart home security hub. The SecuritySystem class detects motion and triggers a public delegate. A junior developer left the delegate field public, meaning external classes can maliciously clear the alert list or trigger fake alarms. You must secure this class and configure a complete utility to test multiple sensor zones.
Task requirements
Secure the
SecuritySystemclass so external code can only subscribe or unsubscribe from the motion alert.In the top-level execution code, subscribe to the alert to print
"Turning on floodlights for {zone}...".Subscribe a second action to print
"Sounding main alarm for {zone}...".Trigger the detection mechanism by calling
DetectMotionfor different zones like “Backyard” and “Garage”.
Constraints
You must use the
eventkeyword to encapsulate theSensorTrippeddelegate inside theSecuritySystemclass.You must use lambda expressions to subscribe to the event.
Good luck trying the exercise! If you’re unsure how to proceed, check the “Solution” tab above.
Get hints
Adding a single keyword to the
SensorTrippeddeclaration insideSecuritySystemwill lock down external access.Since the delegate takes a
stringparameter, your lambda expressions must accept one parameter representing the zone.You cannot invoke an event directly from the top-level code. You must rely on the
DetectMotionmethod to raise the event internally.
Exercise: Security System Alert
Problem statement
You are developing software for a smart home security hub. The SecuritySystem class detects motion and triggers a public delegate. A junior developer left the delegate field public, meaning external classes can maliciously clear the alert list or trigger fake alarms. You must secure this class and configure a complete utility to test multiple sensor zones.
Task requirements
Secure the
SecuritySystemclass so external code can only subscribe or unsubscribe from the motion alert.In the top-level execution code, subscribe to the alert to print
"Turning on floodlights for {zone}...".Subscribe a second action to print
"Sounding main alarm for {zone}...".Trigger the detection mechanism by calling
DetectMotionfor different zones like “Backyard” and “Garage”.
Constraints
You must use the
eventkeyword to encapsulate theSensorTrippeddelegate inside theSecuritySystemclass.You must use lambda expressions to subscribe to the event.
Good luck trying the exercise! If you’re unsure how to proceed, check the “Solution” tab above.
Get hints
Adding a single keyword to the
SensorTrippeddeclaration insideSecuritySystemwill lock down external access.Since the delegate takes a
stringparameter, your lambda expressions must accept one parameter representing the zone.You cannot invoke an event directly from the top-level code. You must rely on the
DetectMotionmethod to raise the event internally.