Quick Answer

Implement the observer pattern with events.

Understanding the Issue

Events allow objects to notify other objects when something happens. Built on delegates, they follow the publisher-subscriber pattern.

The Problem

This code demonstrates the issue:

Csharp Error
// Need to implement a button click event

The Solution

Here's the corrected code:

Csharp Fixed
public class Button
{
    public event EventHandler? Clicked;
    
    public void Press()
    {
        Clicked?.Invoke(this, EventArgs.Empty);
    }
}

// Usage
var button = new Button();
button.Clicked += (sender, e) => Console.WriteLine("Button pressed!");
button.Press();

Key Takeaways

Events enable loose coupling between components.