#368 – How Events Work

An event in C# is a mechanism that allows an object to inform client code about something that happened inside the object that the other code might care about.

For example, you might have a Dog object that raises a Barked event whenever someone calls the dog’s Bark method.  Your code can be notified whenever the dog barks.

In .NET, we say that the Dog object raises the Barked eventThe logging code handles the Barked event in a method known as an event handler.

Events in C# implement something known as the Publish/Subscribe pattern.  The Dog class publishes information about when the dog barks and the logging code subscribes to that information. 

This is also known as the Observer pattern.  The logging code observes the Dog object and the Dog object notifies any observers whenever the dog barks.