Sobes.tech
Junior — Middle

Can you explain what happens by default when processing events in the system?

sobes.tech AI

Answer from AI

By default, in C#, event handling occurs through the delegate and subscriber mechanism. When an event is triggered, all methods subscribed to this event are called sequentially in the order of subscription.

Main points:

  • An event is a special delegate that allows objects to subscribe to notifications.
  • When an event is invoked, all subscribers are called.
  • If no handlers are subscribed, invoking the event does nothing.
  • Exceptions in handlers can interrupt the call chain if not handled.

Example:

public class Publisher
{
    public event EventHandler MyEvent;

    public void RaiseEvent()
    {
        MyEvent?.Invoke(this, EventArgs.Empty);
    }
}

public class Subscriber
{
    public void OnMyEvent(object sender, EventArgs e)
    {
        Console.WriteLine("Event handled");
    }
}

// Usage
var pub = new Publisher();
var sub = new Subscriber();
pub.MyEvent += sub.OnMyEvent;
pub.RaiseEvent();

Thus, by default, all subscribed handlers are called sequentially when an event occurs.