C# Interview Question #58
What is an event in C#?
Exceptions, Delegates, Events & Lambdas Mid-Level Intermediate
Quick Interview Answer
An event provides a publisher-subscriber mechanism built on delegates. A publisher exposes an event, and subscribers register handlers that execute when the event is raised.
Detailed Explanation
An event provides a publisher-subscriber mechanism built on delegates. A publisher exposes an event, and subscribers register handlers that execute when the event is raised.
The event keyword restricts external code from directly invoking or replacing the underlying delegate. Normally only the declaring type can raise the event.
Events are useful for notifications within an application, especially in UI and domain-style designs.
Code Example
public class OrderService
{
public event EventHandler? OrderCompleted;
public void CompleteOrder()
{
// Business logic
OrderCompleted?.Invoke(this, EventArgs.Empty);
}
}