views:

203

answers:

1

I've been trying a good way to memorize how to write events and eventhandlers in C# for a while. Whenever I want to refer to a tutorial on the Internet they tend to be verbose.

The question is how do I write events and eventhandlers in C#? Have you got a code example that illustrates easily how to write such?

+7  A: 

They don't have to be verbose:

// declare an event:
public event EventHandler MyEvent;

// raise an event:
var handler = MyEvent;
if(handler != null) handler(this, EventArgs.Empty);

// consume an event with an anon-method:
obj.MyEvent += delegate { Console.WriteLine("something happened"); };

// consume an event with a named method:
obj.MyEvent += SomeHandler;

void SomeHandler(object sender, EventArgs args) {
    Console.WriteLine("something happened");
}

What is the bit that is being troublesome?

Marc Gravell
+1. I knew either you or Jon would beat me to this one... and give a better answer
Dead account
the bit that is being troublesome are all tutorials that tend to describe delegates as well but all I want is a quick reference
Spoike