DCSIMG
TIP: Dictionary<Type, T> - Use generic type argument as keys - Shimmy on .NET

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

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!
     
Published Monday, May 09, 2011 6:25 AM by Shimmy
תגים:,

Comments

# Generics Typeof T | More More Pics

Wednesday, July 06, 2011 12:35 PM by Generics Typeof T | More More Pics

Pingback from  Generics Typeof T | More More Pics

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above:
Powered by Community Server (Commercial Edition), by Telligent Systems