Here is my code:
var messageHandlers = new Dictionary<Type, Action<T>>();
public static void Subscribe(Action<T> message)
{
if (messageHandlers.ContainsKey(typeof(T)))
{
messageHandlers[typeof(T)] += message;
}
else
{
messageHandlers.Add(typeof(T), message);
}
}
Is there any way to make this a one liner?
You can’t make it a one-liner, but you can make it faster:
The
Dictionary<>indexer will add non-existent keys.If you switch to a
ConcurrentDictionary<>, you can make it a one-liner: