Tuesday, July 27, 2010

C# Readability Tips

Just a couple of C# tips I came across that might improve code readability – these are minor style tips really, nothing too earth-shattering.

Tip 1

For events, in C# before calling the delegate you need to check if anyone is listening to avoid a NullReferenceException, which gets ugly the more events you have (like in an MVP pattern).

if (this.DownloadCompleted != null)
{
this.DownloadStarted(this, e);
}


Instead, declare it with an empty anonymous method as a handler like so…

public event EventHandler DownloadStarted = delegate { };


You no longer need to check if anyone is listening every time you fire the event. (However, your code will call the empty method everytime regardless of whether or not an event is subscribed to.)
this.DownloadStarted(this, e);


However you do need to change how you now check for listeners as you can no longer check for != null as there will always be 1 listener – the anonymous method.

if (this.DownloadCompleted.GetInvocationList().Length == 1)
{
// no one listens to me.
}


Tip 2

You do not need to explicitly declare a new EventHandler () when subscribing to an event

this.applicationUpdaterManager.DownloadStarted +=new DownloadStartedEventHandler(Updater_OnDownloadStarted);


Instead, you can write the following

this.applicationUpdaterManager.DownloadStarted += this.Updater_OnDownloadStarted;


Note: you will still get a compile-time warning if you attempt to wire up a method with a different signature

No comments:

Post a Comment