Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write events and eventhandlers in C#?

Tags:

c#

.net

events

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?

like image 466
Spoike Avatar asked May 13 '09 07:05

Spoike


1 Answers

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?

like image 156
Marc Gravell Avatar answered Oct 11 '22 09:10

Marc Gravell