Tips and tricks (1)

The following code is a straightforward example on how to use the event programming model: the main method is the subscriber that will receive ValidationCompleted notifications, and the Validation class is the publisher that publishes the ValidationCompleted event:

class Program
{
static void Main(string[] args)
{
Validation validation = new Validation();
validation.ValidationCompleted +=
new Validation.ValidationHandler(validation_ValidationCompleted);
validation.Execute();
}
static void validation_ValidationCompleted(object sender,
bool succeeded)
{
Console.WriteLine(string.Format("Validation result: {0}", succeeded));
}
}
public class Validation
{
public delegate void ValidationHandler(object sender, bool succeeded);
public event ValidationHandler ValidationCompleted;
public void Execute()
{
// do some validation here
bool validationSucceeded = true;
SignalValidationCompleted(validationSucceeded);
}
protected void SignalValidationCompleted(bool succeeded)
{
if (ValidationCompleted != null)
{
ValidationCompleted(this, true);
}
}
}

If you run this, the result is what you expect:

 Validation output

Notice in the Validation publisher class the test to check for null:

if (ValidationCompleted != null)
{
ValidationCompleted(this, true);
}

You have to do this because when there are no subscribers, the ValidationCompleted event will be null.

A nice trick to avoid the need for this null-test, is to add an empty delegate to the event declaration:

public event ValidationHandler ValidationCompleted = delegate {};

This way, the event will never be null and you can just call it:

protected void SignalValidationCompleted(bool succeeded)
{
ValidationCompleted(this, true); // No null check needed anymore
}

A nice little trick.

Advertisements

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