Difference between delegate and event:

As you might have wondered, if an event is a kind of delegate, why do we need an event where a delegate can fulfil the purpose?

Suppose, if we don't use the event keyword in the above example and use only delegate, for example:

Event without event keyword:

public class PrintHelper
{
    public delegate void BeforePrint(string message);
    public BeforePrint beforePrintEvent;

    public PrintHelper()
    {

    }

    public void PrintNumber(int num)
    {
        if (beforePrintEvent != null)
            beforePrintEvent.Invoke("PrintNumber");

        Console.WriteLine("Number: {0,-12:N0}", num);            
    }

    public void PrintDecimal(int dec)
    {
        if (beforePrintEvent != null)
            beforePrintEvent("PrintDecimal");

        Console.WriteLine("Decimal: {0:G}", dec);
    }

    public void PrintMoney(int money)
    {
        if (beforePrintEvent != null)
            beforePrintEvent.Invoke("PrintMoney");

        Console.WriteLine("Money: {0:C}", money);
    }

    public void PrintTemperature(int num)
    {
        if (beforePrintEvent != null)
            beforePrintEvent("PrintTemerature");

        Console.WriteLine("Temperature: {0,4:N1} F", num);
    }
    public void PrintHexadecimal(int dec)
    {
        if (beforePrintEvent != null)
            beforePrintEvent("PrintHexadecimal");

        Console.WriteLine("Hexadecimal: {0:X}", dec);
    }
}

Now you can assign handler methods to the delegate using the "+=" operator as we do with a multicast delegate. But some subscriber class can, by mistake, assign methods to the delegate using the "=" operator and make it a single delegate handler; now all the other methods assigned to the delegate will get overridden.

Subscribe event:

_printHelper.beforePrintEvent = printHelper_beforePrintEvent;

We can overcome this problem by using events. It uses AddEventHandler() and RemoveEventHandler() methods to assign or remove methods to the delegate. The "+=" operator overloads for the AddEventHandler method and "-=" operator overloads for the RemoveEventHandler method. The event doesn't allow the "=" operator to assign methods to the event delegate.

The following is an example of how an event adds event handler to the publisher.

Event internal implementation:

readonly object eventLock = new object();

event BeforePrint BeforePrintEvent
{
    add
    {
        lock (eventLock)
        {
            BeforePrintEvent += value;
        }
    }
    remove
    {
        lock (eventLock)
        {
            BeforePrintEvent -= value;
        }
    }
}

In short, event internally maintains delegate methods chain subscribed by consumers by using AddEventHandler and RemoveEventHandler, also by overloading += and -+ operators.