0

Yes, alright, it is probably a stupid question but I can´t understand events. I mean that I understand what delegates are for, I can create avents and handle them but I don´t actually understand them. Let´s say I have the following code with event in the Form1.cs file:

private void btnSleep_Click(object sender, EventArgs e)
{
        _currentPerson.Sleep();
}    

private void lvPeople_SelectedIndexChanged(object sender, EventArgs e)
{
        if (lvPeople.SelectedItems.Count > 0)
            {
            _currentPerson = (Person)lvPeople.SelectedItems[0].Tag;
            _currentPerson.FellAsleep += _currentPerson_FellAsleep;
        }
}

void _currentPerson_FellAsleep(object sender, EventArgs e)
{
        lvPeople.SelectedItems[0].BackColor = Color.Aqua;
}

In the Person class I have this:

public delegate void PersonEventsHandlers(Object sender, EventArgs e);
public event PersonEventsHandlers FellAsleep;
public void Sleep()
{
        this._isSleeping = true;
        FellAsleep(this, EventArgs.Empty);
}

So everything works fine, cool. But if I do this change and forget the Person events works anyways.

private void btnSleep_Click(object sender, EventArgs e)
{
        _currentPerson.Sleep();
         lvPeople.SelectedItems[0].BackColor = Color.Aqua;
}

So why should I use the Person events?!

Thank you.

Mario Lopez
  • 1,405
  • 13
  • 24
  • Events allow one form of decoupling - any consumer can listen to events from a producer. The consumer might be another (external) object. This example is trivialized and makes some assumption about the scope of the events (and possible listeners). Take a simple Timer object, for instance - why does it have a Tick event (which is specialized: it only applies to timers), and what is it useful for? How could such a Timer be used/implemented without [specialized] Events? – user2246674 Jun 16 '13 at 05:26
  • See this http://stackoverflow.com/questions/29155/what-are-the-differences-between-delegates-and-events – The Muffin Man Jun 16 '13 at 06:11

1 Answers1

2

Events are all about deferred execution... I want to define the behaviour of something but not execute it right now... later under certain conditions. It is a way to register lazy functionality that is executed when needed.

This is especially useful when distributing a compiled assembly. People can add to the functionality of your assembly without recompilation.

Haney
  • 32,775
  • 8
  • 59
  • 68
  • 1
    Thanks for the explanation. I have found a good resource here: [link](http://stackoverflow.com/questions/803242/understanding-events-and-event-handlers-in-c-sharp) – Mario Lopez Jun 17 '13 at 10:38