fork(1) download
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. public class Test
  5. {
  6. public static void Main()
  7. {
  8. // your code goes here
  9. Messenger m = new Messenger();
  10. var sum = 0;
  11. Action<int> messenger = x => sum += x;
  12. m.Register<int>(messenger);
  13. m.Send(42);
  14. Console.WriteLine(sum);
  15. m.Unregister<int>(messenger);
  16. m.Send(23);
  17. Console.WriteLine(sum);
  18. }
  19. }
  20.  
  21. /// <summary>
  22. /// Strongly-typed messenger system.
  23. /// </summary>
  24. public class Messenger
  25. {
  26. /// <summary>
  27. /// The actions. These are called when a message is sent.
  28. /// </summary>
  29. private readonly IDictionary<Type, Delegate> actions = new Dictionary<Type, Delegate>();
  30.  
  31. /// <summary>
  32. /// Register an action for a message.
  33. /// </summary>
  34. /// <typeparam name="T"> Type of message to receive. </typeparam>
  35. /// <param name="action"> The action that is executed when the message is received. </param>
  36. public void Register<T>(Action<T> action)
  37. {
  38. if (action == null)
  39. {
  40. throw new ArgumentNullException("action");
  41. }
  42.  
  43. var messageType = typeof(T);
  44.  
  45. if (actions.ContainsKey(messageType))
  46. {
  47. actions[messageType] = Delegate.Combine(actions[messageType], action);
  48. }
  49. else
  50. {
  51. actions.Add(messageType, action);
  52. }
  53. }
  54.  
  55. /// <summary>
  56. /// Sends the specified message.
  57. /// </summary>
  58. /// <typeparam name="T"> The type of message. </typeparam>
  59. /// <param name="message"> The message to send. </param>
  60. public void Send<T>(T message)
  61. {
  62. var messageType = typeof(T);
  63.  
  64. if (actions.ContainsKey(messageType))
  65. {
  66. ((Action<T>)actions[messageType])(message);
  67. }
  68. }
  69.  
  70. /// <summary>
  71. /// Unregister an action.
  72. /// </summary>
  73. /// <typeparam name="T"> The type of message. </typeparam>
  74. /// <param name="action"> The action to unregister. </param>
  75. public void Unregister<T>(Action<T> action)
  76. {
  77. var messageType = typeof(T);
  78.  
  79. if (actions.ContainsKey(messageType))
  80. {
  81. actions[messageType] = (Action<T>)Delegate.Remove(actions[messageType], action);
  82. }
  83. }
  84. }
Runtime error #stdin #stdout #stderr 0.05s 27256KB
stdin
Standard input is empty
stdout
42
stderr
Unhandled Exception:
System.NullReferenceException: Object reference not set to an instance of an object
  at Messenger.Send[Int32] (Int32 message) [0x00000] in <filename unknown>:0 
  at Test.Main () [0x00000] in <filename unknown>:0 
[ERROR] FATAL UNHANDLED EXCEPTION: System.NullReferenceException: Object reference not set to an instance of an object
  at Messenger.Send[Int32] (Int32 message) [0x00000] in <filename unknown>:0 
  at Test.Main () [0x00000] in <filename unknown>:0