implement a observer pattern in csharp

One way to implement the observer pattern in C# is to use delegates and events. Here's an example:

main.cs
public delegate void EventHandler<T>(T sender, EventArgs args);

public class Subject
{
    public event EventHandler<EventArgs> Updated;

    private void Notify()
    {
        Updated?.Invoke(this, EventArgs.Empty);
    }

    public void DoSomething()
    {
        // do something
        Notify();
    }
}

public class Observer
{
    public Observer(Subject subject)
    {
        subject.Updated += OnUpdate;
    }

    private void OnUpdate(Subject sender, EventArgs args)
    {
        // do something in response to the update
    }
}
546 chars
31 lines

In this example, the Subject class has an Updated event that observers can subscribe to. The Notify method is called whenever the subject is updated, which invokes the Updated event and notifies all subscribed observers. The Observer class is an example observer that subscribes to the Updated event in its constructor, and defines a OnUpdate method to be called in response to updates.

gistlibby LogSnag