Observer Pattern with C# Events & Delegates


Events and delegates in C# are important concepts in software development processes. Especially for implementing the Observer Pattern, using C# events and delegates increases the flexibility and extensibility of our applications. In this post, we will explore how the Observer Pattern works with C# event and delegate structures.

What are C# Events and Delegates?

Delegates are types that hold a reference to a method. Through this reference, a delegate can easily access a method. Events, on the other hand, are a special type derived from a delegate and are generally triggered for changes in the state of an object. This structure allows us to create dynamic and flexible software designs.

Defining Delegates

The following example demonstrates how a delegate can be defined and used:

delegate void Notify();

class Process{ 
    public event Notify ProcessCompleted;

    public void StartProcess() {
        // Operations
        OnProcessCompleted();
    }

    protected virtual void OnProcessCompleted() {
        ProcessCompleted?.Invoke();
    }
}

Implementing the Observer Pattern in C#

The Observer Pattern ensures that other objects interested in changes to the state of an object can be updated. This application is especially used in GUI applications or data updates.

Observer Pattern Example

The code example below shows a simple application that notifies listeners (Observers) when a process is completed:

class Observer { 
    public void Subscribe(Process process) {
        process.ProcessCompleted += Notify;
    }

    private void Notify() {
        Console.WriteLine("Process completed!");
    }
}

class Program {
    static void Main(string[] args) {
        Process process = new Process();
        Observer observer = new Observer();
        observer.Subscribe(process);

        process.StartProcess();
    }
}

Conclusion

Event and delegate structures in C# play an important role in implementing the Observer Pattern. This method provides better structure and organization in our software applications, reduces code repetition, and makes maintenance easier. Developing an effective observer pattern using C# will help you increase flexibility in your software projects.