Pattern for dealing with null handler for events in C#

If you’ve used events in C# before, you’ve probably written code like this too:

public event EventHandler Started;
...
// make sure Started is not null before firing the event
// else, NullReferenceException will be thrown
if (Started != null)
{
    Started(this, some_event_args);
}

This is perfectly ok and normal to do, but can quickly become tiresome if you have to fire events in multiple places in your code and have to do a null reference check every time!

So instead, I have been using this pattern for a while:

// initialise with empty event hanlder so there's no need for Null reference check later
public event EventHandler Started = (s, e) => { };
...
// no need for Null reference check anymore as Started is never null
Started(this, some_event_args);

If all you need is the ability to add/remove handlers, then this pattern would do you fine as the event will never be null because there’s no way for you to remove the anonymous method the event was initialised with unless you set the event to null.

However, if you occasionally need to clear ALL the event handlers and set the event to null, then don’t use this pattern as you might start seeing NullReferenceException being thrown before you add event handlers back in.

Buzzword Buster – IoC

Definition:

Inversion of Control (IoC) refers to the inversion of the flow of control (the order in which individual statements, function calls, etc. are executed) in a software. You’ll often hear the term Hollywood principle being mentioned in the same breath as IoC, it simply states "Don’t call us, we’ll call you" which more or less sums up the principles of IoC.

Purpose:

In traditional software design, the flow of control is governed by a central piece of code which often have to address multiple concerns (logging, validation, etc.) and need to be aware of the implementation details of its dependencies. This creates a very tightly coupled application where changes in one component have a ripple effect throughout the rest of the application.

Following the principles of IoC can help you achieve:

  • decoupling of execution of a task from implementation (through the use of interfaces)
  • greater separation of concerns (each component only focuses on what it’s designed to do)
  • more flexibility (implementation can be easily changed without any side effects on other components)
  • more testable code (enables the use of stubs/mocks in place of concrete classes intended for production)

Advantages:

  • Simplifies the building of specific tasks.

Disadvantages:

  • Has the potential to make the flow of control in an application more complex, and therefore making it harder to follow.

Parting thoughts..

  • Misusing or abusing IoC can result in Macaroni code.
  • IoC is not a silver bullet for all your system engineering problems, and remember, "Don’t fix what’s not broken"
  • When adopting IoC, there is additional training needs for new joiners to the team.
  • Design systems for flexibility, which allows quick adaptation to changing environment/requirementsimage
  • Avoid complicating system design by trying to be future-proof upfront, you can’t predict the future! image

Further readings:

.NetRocks show 362 – James Kovac Inverts our Control!

Loosen Up – Tame Your Software Dependencies For More Flexible Apps (MSDN article by James Kovac)

Design Pattern – Inversion of Control and Dependency Injection (by Shivprasad Koirala)

The C# Dispose Pattern

The Dispose pattern is something we’ve all seen before, and it’s so tried and tested most of us (especially myself!) have been more than happy to apply without question.

Whilst reading various blogs/articles I came across some differing opinion about this well known pattern and started to question what I had taken for granted myself.

After some more research and a question on the goldmine of knowledge that is the StackOverflow I have shortlisted a few points you should consider when implementing the standard C# dispose pattern:

  1. if your object doesn’t hold any IDisposable objects or unmanaged resources (DB connection, for example) then you don’t need to implement the IDisposable or finalizer at all
  2. if your object doesn’t hold any unmanaged resources then don’t implement a finalizer, the Garbage Collector won’t attempt to finalize your object (which has a performance hit) unless you have implemented a finalizer.
  3. don’t forget to call Dispose() on each of the IDisposable objects in the Dispose(bool) method.
  4. if your object holds unmanaged resources, clean them up in the finalizer without re-writing any of the cleanup code in the Dispose(bool) method already.

So for a simple class with no unmanaged resources and a collection of IDisposable objects, your class might look something like this:

public sealed class MyClass : IDisposable
{
     IList<MyObject> objects;  // MyClass holds a list of objects
     private bool _disposed;   // boolean flag to stop us calling Dispose(twice)

     public void Dispose()
     {
          Dispose(true);
          GC.SuppressFinalize(this);
     }

     private void Dispose(bool disposing)
     {
          if (!_disposed)
          {
               // call Dispose on each item in the list
               if (disposing)
               {
                    foreach (var o in objects)
                    {
                         // check if MyObject implements IDisposable
                         var d = o as IDisposable();
                         if (d != null) d.Dispose();
                    }
               }
          _disposed = true;
          }
     }
}

This is fairly similar to the standard C# Dispose pattern, the main difference being the lack of a finalizer because remember, implementing a finalizer will impact the performance of your type so don’t implement it unless you need it.