using System.Collections.Generic;
public static void Main()
var cache = new TypeKeyedDictionary<ITom>();
var tomTom = new TomTom();
ITom tomtomtom = cache.Get<Tom>();
catch (KeyNotFoundException e)
tomtomtom = cache.Get<TomTom>();
Console.WriteLine("I'm Tom");
public class TomTom : ITom
Console.WriteLine("I'm TomTom");
public class TypeKeyedDictionary<T> where T : class
private readonly IDictionary<Type, T> _dictionary;
public TypeKeyedDictionary()
_dictionary = new Dictionary<Type, T>();
public void Set<TValue>(TValue value) where TValue : T
Type type = typeof(TValue);
_dictionary[type] = value;
public TValue Get<TValue>() where TValue : T
Type type = typeof(TValue);
if (Has<TValue>() == false)
throw new KeyNotFoundException(string.Format("Type {0} does not exist in dictionary", type));
return (TValue) _dictionary[type];
public void Remove<TValue>() where TValue : T
Type type = typeof(TValue);
_dictionary.Remove(type);
public bool Has<TValue>() where TValue : T
Type type = typeof(TValue);
return _dictionary.ContainsKey(type);