System Members - Events

Events are a mechanism in C# that allow a class to notify other classes when something significant happens. They are based on delegates and provide a way to implement the observer pattern.

Events enable loosely coupled communication between objects, where an object that raises an event does not need to know which objects are listening or how they will react.

EventName Event

Namespace: System

Description: This is a placeholder for a common event. In a real documentation, specific events would be listed here with their detailed descriptions.

Signature:

public event EventHandler EventName;

Event Handlers

  • EventHandler: The delegate type that defines the signature of the event handler methods.

Fired When:

  • A specific condition or action occurs within the object raising the event.

AnotherCustomEvent Event

Namespace: System

Description: Represents a custom event, often used for application-specific notifications or user interactions.

Signature:

public event CustomEventHandler CustomEventHandlerName;

Event Handlers

  • CustomEventHandler: A custom delegate type, potentially with different parameters than the standard EventHandler.

Fired When:

  • A custom process completes.
  • A user performs a specific, non-standard action.

Common Event Scenarios

  • UI Events: Button clicks, mouse movements, keyboard input.
  • Data Change Events: Notification when data in a collection is added, removed, or modified.
  • Operation Completion Events: Signifying that a long-running operation has finished.
  • System Notifications: Alerts about system status or errors.

Raising and Handling Events

An object raises an event by invoking its delegate. An event handler is a method that matches the delegate's signature and is registered with the event.


// Example of raising an event
public class MyPublisher {
    public event EventHandler DataChanged;

    protected virtual void OnDataChanged(EventArgs e) {
        EventHandler handler = DataChanged;
        if (handler != null) {
            handler(this, e);
        }
    }

    public void ChangeData() {
        // ... data modification logic ...
        OnDataChanged(EventArgs.Empty);
    }
}

// Example of handling an event
public class MySubscriber {
    public void Subscribe(MyPublisher publisher) {
        publisher.DataChanged += HandleDataChanged;
    }

    private void HandleDataChanged(object sender, EventArgs e) {
        Console.WriteLine("Data has been changed!");
    }
}