fork download
  1. using System;
  2.  
  3. public class Events
  4. {
  5. public delegate void MyAction();
  6.  
  7. public event MyAction OriginalEvent = delegate { };
  8. public event Action DelegatingEvent
  9. {
  10. add { OriginalEvent += new MyAction(value); }
  11. remove { OriginalEvent -= new MyAction(value); }
  12. }
  13.  
  14. public void FireOriginalEvent()
  15. {
  16. OriginalEvent();
  17. }
  18. }
  19.  
  20. public class Test
  21. {
  22. private static void PrintFoo()
  23. {
  24. Console.WriteLine("Foo");
  25. }
  26.  
  27. public static void Main()
  28. {
  29. Console.WriteLine("Testing original event:");
  30. Events events1 = new Events();
  31.  
  32. events1.OriginalEvent += PrintFoo;
  33. events1.OriginalEvent -= PrintFoo;
  34. events1.FireOriginalEvent();
  35.  
  36. Console.WriteLine("Testing delegating event:");
  37. Events events2 = new Events();
  38.  
  39. events2.DelegatingEvent += PrintFoo;
  40. events2.DelegatingEvent -= PrintFoo; // Doesn't actually remove anything!
  41. events2.FireOriginalEvent();
  42.  
  43. Console.WriteLine("However, THIS works:");
  44. Events events3 = new Events();
  45.  
  46. Action printFooAction = PrintFoo;
  47. events3.DelegatingEvent += printFooAction;
  48. events3.DelegatingEvent -= printFooAction;
  49. events3.FireOriginalEvent();
  50. }
  51. }
Success #stdin #stdout 0.02s 33880KB
stdin
Standard input is empty
stdout
Testing original event:
Testing delegating event:
Foo
However, THIS works: