Example of subscribing to and firing events


/ Published in: C#
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. using System;
  2.  
  3. namespace testConsole
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. Test myTest = new Test();
  10. // Add event handler to the event
  11. myTest.TestEvent += new EventHandler(myTest_TestEvent);
  12. myTest.fireEvent();
  13. Console.ReadLine(); // Keep console window open
  14. }
  15.  
  16. static void myTest_TestEvent(object sender, EventArgs e)
  17. {
  18. if (e is TestEventArgs)
  19. {
  20. TestEventArgs data = e as TestEventArgs;
  21. Console.WriteLine(data.Message);
  22. }
  23. }
  24. }
  25.  
  26. class Test
  27. {
  28. public event EventHandler TestEvent;
  29. public Test()
  30. {
  31. }
  32. public void fireEvent()
  33. {
  34. // Always check if the EventHandler is null (no subscribers)
  35. var handler = TestEvent;
  36. if (handler != null)
  37. {
  38. handler(this, new TestEventArgs("Event Fired"));
  39. }
  40. }
  41. }
  42.  
  43. class TestEventArgs : EventArgs
  44. {
  45. public string Message { get; private set; }
  46. public TestEventArgs(string message)
  47. {
  48. this.Message = message;
  49. }
  50. }
  51. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.