How to write events and event handlers in C #?

I tried to remember well how to write events and event handlers in C # for a while. Whenever I want to turn to a textbook on the Internet, they are usually verbose.

The question is how to write events and event handlers in C #? Do you have sample code that easily illustrates how to write such?

+4
source share
2 answers

They do not have to be detailed:

// 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 a bit of concern?

+9
source

Once you get the appetite, try this:

For VS2005: A Practical Guide. Publishing Events That Follow the .NET Framework Recommendations (C # Programming Guide) http://msdn.microsoft.com/en-us/library/w369ty8x(v=vs.80).aspx

For Visual Studio 11: http://msdn.microsoft.com/en-us/library/w369ty8x(v=vs.110).aspx

+1
source

All Articles