TIP: Dictionary<Type, T> – Use generic type argument as keys

09/05/2011

no comments

When you want to store items by known types using the type as the key, you could add some methods to the Dictionary<,> class to make this work the generic way.

It basically does nothing but does the typeof(MyType) for you.

Note: Didn’t test performance impacts.

using System.Collections.Generic;

namespace System.Collections.Specialized
{
  public class TypeDictionary<TValue> : Dictionary<Type, TValue>
  {
    public TValue Get<T>()
    {
      return this[typeof(T)];
    }

    public void Add<T>(TValue value)
    {
      Add(typeof(T), value);
    }

    public bool Remove<T>()
    {
      return Remove(typeof(T));
    }

    public bool TryGetValue<T>(out TValue value)
    {
      return TryGetValue(typeof(T), out value);
    }

    public bool ContainsKey<T>()
    {
      return ContainsKey(typeof(T));
    }
  }
}

 
This time I have a certificate too!
     
Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>