What Are Events?

Town Crier

Hear ye, Hear ye, an event has happened

The 16th century Latin word for event is eventus which means ‘result or happen’. The dictionary defines an event as something that occurs in a certain place during a particular interval of time. Microsoft defines events in the C# Programming Guide like this; “Events enable a class or object to notify other classes or objects when something of interest occurs. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers.”

As developer, I think we use events everyday without understanding what an event actually is. The event is a way for a class or an object to talk back to the consumer or observer of the class.  The following example is a simple class called Dog.  It will speak and once, it has it will raise the event HasSpoken.

public class Dog {
    public string Name { get; set; }

    public event EventHandler HasSpoken;

    public void Speak(string what = "woof") {
        Console.WriteLine(what);

        if (HasSpoken != null)
            HasSpoken(this, EventArgs.Empty);
    }
}

The “Dog” is only speaking here because I am invoking it to do so. However, something could happen at any time and an event will be raised as a communication mechanism back to me so that I can handle something. Its timing is known to you, because it happens after something, but there could be many things between when it was raised and when you actually began handling it. Notice that that we have to check to see if HasSpoken is null first before we raise the event so that we don’t get an exception.

        Console.WriteLine(what);

        if (HasSpoken != null)
            HasSpoken(this, EventArgs.Empty);

Now that we have the null check in place, I can raise the event all I want. This helps with performance too because any time because your not raising events when nobody is listening for it. This is implementation conforms to the “Publish Subscribe Pattern”.

How many people can listen to an event?

More than one!
Events and Delegates in .NET are what are what is called multicasting objects. Event delegates are multicast, which means that they can hold references to more than one event handling method. Read more about events and delegates here

Now the event HasSpoken is a list of methods that need to be called when you raise the event. This is why the variable is null when no one is listening. It does not contain any items because there are no methods to reference.

How can I listen to the event?

You can listen to an event in .NET by subscribing to the event. In C# you must actively listen to the event by creating a new object and subscribing to the object explicitly. In the sample below I’m going to create a new person and have them listen for the dog we created above.

public class Person {
    public Dog Pet { get; set; }

    public Person() {
        Pet = new Dog() { Name = "Lassie" };
        Pet.HasSpoken += Pet_HasSpoken;
    }

    private void Pet_HasSpoken(object sender, EventArgs e) {
        throw new NotImplimentedException();
    }
}

As you can see the compiler put a new NotImplimentedException so that we don’t get lazy. You can put whatever you want in here such as calling a method on Person that would pet the dog. That part is up to you. I hope this has shed some light on events in .NET. Drop me a line and let me know if you like it.

Until next time…

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