Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is keyword 'event' optional in C#?

What is the difference between eventOne (with keyword 'event') and eventTwo (w/o keyword)?

class Program
{
    public event EventHandler eventOne;
    public EventHandler eventTwo;

    public void RaiseOne()
    {
        if (eventOne != null)
            eventOne(this, EventArgs.Empty);
    }

    public void RaiseTwo()
    {
        if (eventTwo != null)
            eventTwo(this, EventArgs.Empty);
    }

    static void Main(string[] args)
    {
        var p = new Program();
        p.eventOne += (s, e) => Console.WriteLine("One");
        p.eventTwo += (s, e) => Console.WriteLine("Two");
        p.RaiseOne();
        p.RaiseTwo();
    }
}
like image 440
Prankster Avatar asked Apr 02 '09 21:04

Prankster


2 Answers

  • eventOne is a public event backed by a private field of type EventHandler.
  • eventTwo is a public field of type EventHandler.

Basically an event only encapsulates the ideas of "subscribe" and "unsubscribe" in the same way that a property only encapsulates the ideas of "get" and "set" rather than the actual storage. (As far as the CLR is concerned an event can also expose a "raise" method, but C# never uses this. Ignore it.)

See my article on events (alternate link) for more about the difference between delegates and events.

like image 127
Jon Skeet Avatar answered Sep 18 '22 12:09

Jon Skeet


By using the event keyword you tell C# go generate to hidden methods, add_XXX and remove_XXX for your underlying delegate. This makes sure that anyone using your class can only attach and remove delegates to the event. The key point is that nobody outside your class and raise the event, so you've got complete control over when this will happen.

If you don't use event then you're just exposing a public delegate that anyone can add to, remove from and invoke. It's highly unlikely that you want anyone other than your class to do the invoking.

like image 29
Sean Avatar answered Sep 19 '22 12:09

Sean