Reputation: 121762
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?
Upvotes: 6
Views: 8301
Reputation: 21
Once you get an appetite, try this out:
For VS2005: How to: Publish Events that Conform to .NET Framework Guidelines (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
Upvotes: 1
Reputation: 1062620
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?
Upvotes: 13