/ Published in: C#
See [Raise and Handle Events Generically](http://snipplr.com/view/15033/raise-and-handle-events-generically/) for a better way to use events (generically) and links to best practices in .NET events.
This example should be used as a Console program and will simply write a line of text to the console. It shows how to create an event handler in a class, have that event handler fire an event with custom information, and how to subscribe to that event and use its data. I hope it is straightforward enough.
This example should be used as a Console program and will simply write a line of text to the console. It shows how to create an event handler in a class, have that event handler fire an event with custom information, and how to subscribe to that event and use its data. I hope it is straightforward enough.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
using System; namespace testConsole { class Program { static void Main(string[] args) { // Add event handler to the event myTest.fireEvent(); Console.ReadLine(); // Keep console window open } static void myTest_TestEvent(object sender, EventArgs e) { { TestEventArgs data = e as TestEventArgs; Console.WriteLine(data.Message); } } } class Test { public event EventHandler TestEvent; public Test() { } public void fireEvent() { // Always check if the EventHandler is null (no subscribers) var handler = TestEvent; if (handler != null) { } } } class TestEventArgs : EventArgs { public string Message { get; private set; } public TestEventArgs(string message) { this.Message = message; } } }