C# Interview Question #59

What is the difference between a delegate and an event?

Exceptions, Delegates, Events & Lambdas Mid-Level Intermediate

Quick Interview Answer

A delegate is a type-safe method reference that can be assigned and invoked according to its accessibility. An event is a restricted publisher-subscriber abstraction built on a delegate.

Detailed Explanation

A delegate is a type-safe method reference that can be assigned and invoked according to its accessibility. An event is a restricted publisher-subscriber abstraction built on a delegate.

With an event, outside consumers can normally subscribe using += and unsubscribe using -=, but they cannot raise the event directly. This protects the publisher's control over when notifications occur.

Use delegates for callbacks and function values. Use events when an object should publish notifications to subscribers.

Code Example

public delegate void Notify(string message);

public class Publisher
{
    public event Notify? Notification;

    public void Publish(string message)
    {
        Notification?.Invoke(message);
    }
}