Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Raising an event in C#

0.00/5 (No votes)
16 Aug 2013 1  
Raising an event in C#, methods and Critics

Introduction

During this years, I come across many habits of developers regarding raising an Event, In the present Post I will try to summarize all those ways and give some critics.

Code

  1. The first and intuitive way is to declare and use the event directly like in the example below :
  2. public class Foo
    {
      public event EventHandler FooEvent;
      public Foo()
      {
      }
      public void Execute()
      {
        //Do the work
        if (FooEvent != null)
          FooEvent(this, new EventArgs());
        //Continue the work
      }
    } 

    The problem with this is you have to test if the event is not null. and you might forget about it easily.

  3. The second approach is to create a function that raise the event for you:
    public class Foo
    {
      public event EventHandler FooEvent;
      public Foo()
      {
    
      }
      protected void OnFooEvent()
      {
        if (FooEvent == null)
          return;
        FooEvent(this, new EventArgs());
      }
      public void Execute()
      {
        //Do the work
        OnFooEvent();
        //Continue the work
      }
    }     

    Although this simplify the way we call the event but we are always able to call the event directly and so we may have a NullReferenceException. also we should define a function that raises the event in every class.

  4. The third way is a good way to be sure that we won't have a NullReferenceException.
    public class Foo
    {
      public event EventHandler FooEvent = new EventHandler((e, a) => { });
      public Foo()
      {
        
      }      
      public void Execute()
      {
        //Do the work
        FooEvent(this, new EventArgs());
        //Continue the work
      }
    }  

    With this way, we will never have a risk of NullReferenceException.

  5. The forth way is to create an extension function that raises the event and use it.
  6. public static class EventHelper
    {
      public static void Raise(this EventHandler eventHandler, object sender,EventArgs args)
      {
        if (eventHandler == null)
          return;
        eventHandler(sender, args);
      }
    }
    
    public class Foo
    {
      public event EventHandler FooEvent;
      public Foo()
      {
        
      }      
      public void Execute()
      {
        //Do the work
        FooEvent.Raise(this, new EventArgs());
        //Continue the work
      }
    }

The advantages of this way is the readability, also the null check is centralized.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here