The significance of the C# event keyword

Andrew Phillips asked on my CodeProject article Events and event handling in C# forum whether delegates alone aren’t sufficient for event handling and what the purpose of the event keyword is. Here is his post in it’s entirety:-

OK, I understand delegates but there is a basic thing about events that no books, articles etc ever explain. What is the purpose of the “event” keyword. I have tried example code that demonstrates events and they all continue to work if you remove the “event” keyword from the declaration of the delegate.

It seems to me that delegates are sufficient for implementing event-handling code. I can’t see the purpose of the “event” keyword. What am I missing?

Andrew Phillips

Here is the answer I posted for him :-

Hi Andrew

There is a subtle difference between using the event keyword and not using the event keyword.

When you access the Event member from outside the class, the “event” keyword prevents you from both invoking the event as well as from setting the event to null. But if you remove the event keyword, you can set the delegate to null or even invoke the delegate directly.

So essentially the event keyword protects the event from being invoked or set to null from outside of the class.

Hope you understood what I said.

Regards
Nish

p.s. Good question by the way. After 2+ years I am glad someone read my article well enough to want to ask such a question

I thought it was an interesting enough issue and that it deserved a blog entry here. In fact here is some sample code to make things clearer.

/// <summary>
/// The delegate that will represent
/// the event handler
/// </summary>
public delegate void DivBySevenHandler(object o,
  DivBySevenEventArgs e);

/// <summary>
/// The EventArgs derived class that I use
/// to pass info to the event
/// </summary>
public class DivBySevenEventArgs : EventArgs
{
  public readonly int TheNumber;

  public DivBySevenEventArgs(int num)
  {
    TheNumber = num;
  }
}

/// <summary>
/// The listener class to whose member function
/// I hook my event to
/// </summary>
public class DivBySevenListener
{
  public void ShowOnScreen(object o, DivBySevenEventArgs e)
  {
    Console.WriteLine(
      "divisible by seven event raised!!!" +
      " the guilty party is {0}",
      e.TheNumber);
  }
}

/// <summary>
/// The class that has an event, a function
/// that raises the event and the event handler method
/// </summary>
public class Buster
{
  public event DivBySevenHandler EventSeven;

  public void OnEventSeven(DivBySevenEventArgs e)
  {
    if(EventSeven!=null)
      EventSeven(new object(),e);
  }

  public void GenNumbers()
  {
    for(int i=0;i<99;i++)
    {
      if(i%7==0)
      {
        DivBySevenEventArgs e1 = new DivBySevenEventArgs(i);
        OnEventSeven(e1);
      }
    }
  }
}

Now for some sample code that uses the class and raises an event :-

public class Nish
{
  public static void Main()
  {
    Buster b = new Buster();
    DivBySevenListener dbsl = new DivBySevenListener();
    b.EventSeven += new DivBySevenHandler(
      dbsl.ShowOnScreen);
    b.GenNumbers();
    //b.EventSeven(null,new DivBySevenEventArgs(11));
    //b.EventSeven = null;
  }
}

Lines 10 and 11 will not compile which is a very good thing. You certainly wouldn’t want people setting your event object to null or invoking your event handler directly. If you remove the event keyword from the declaration, you’ll find that both the above operations are allowed which can prove to be very nasty as far as end-results go.

So, there you go Andrew – now you know the importance of using the event keyword 🙂

Advertisements

7 thoughts on “The significance of the C# event keyword

  1. Just out of curiosity…

    I *completely* understand the prevention of invocation outside the class, but given that there is almost always a null check before invocation, why is preventing the event object being set to null such a good thing?

  2. Maybe because if you set it to null, you would cancel other people’s subscriptions to the event, which may cause code to break or do undesired things.

  3. There is more to event keyword then only invocation restriction.

    Event keyword allows the delegate declaration to be included in an interface specification unlike other fields and delegates which are not allowed.

    Second is that event keyword adds accessor method for the event which are just like properties for the fields. While properties have get and set, event accessors have add and remove.

  4. Another small significance of event keyword is, VS IDE recognize it. If you specify a delegate with event keyword, Class view displays it with lightning symbol. With out event keyword, the delegate is displayed with field symbol.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s