Mapping from a type to an instance of that type
A question came up on Stack Overflow yesterday which I've had to deal with myself before now. There are times when it's helpful to have one value per type, and that value should be an instance of that type. To express it in pseudo-code, you want an IDictionary<typeof(T), T> except with T varying across all possible types. Indeed, this came up in Protocol Buffers at least once, I believe.
.NET generics don't have any way of expressing this, and you end up with boxing and a cast. I decided to encapsulate this (in MiscUtil of course, although it's not in a released version yet) so that I could have all the nastiness in a single place, leaving the client code relatively clean. The client code makes calls to generic methods which either take an instance of the type argument or return one. It's a really simple class, but a potentially useful one:
public class DictionaryByType
{
private readonly IDictionary<Type, object> dictionary = new Dictionary<Type, object>();
public void Add<T>(T value)
{
dictionary.Add(typeof(T), value);
}
public void Put<T>(T value)
{
dictionary[typeof(T)] = value;
}
public T Get<T>()
{
return (T) dictionary[typeof(T)];
}
public bool TryGet<T>(out T value)
{
object tmp;
if (dictionary.TryGetValue(typeof(T), out tmp))
{
value = (T) tmp;
return true;
}
value = default(T);
return false;
}
}
It doesn't implement any of the common collection interfaces, because it would have to do so in a way which exposed the nastiness. I'm tempted to make it implement IEnumerable<KeyValuePair<Type, object>> but even that's somewhat unpleasant and unlikely to be useful. Easy to add at a later date if necessary.
(I know the XML documentation leaves something to be desired. One day I'll learn how to really do it properly - currently I fumble around if I'm trying to refer to other types etc within the docs.)