Search code examples
c#genericsgeneric-collections

query a dictionary for unique generic objects


I am trying to write a generic method that returns a generic object. The method will take the generic type and use it to query a collection, for the object with the matching type.

I have made an attempt but there is a compilation error, when trying to add this object to a collection. cannot convert from CustomSet<AppLog>' to 'CustomSet<System.Type>'

How can I meet this specification?

public CustomSet<TEntity> Set<TEntity>() where TEntity : class
{
    Type key = typeof(TEntity);

    if (allSets.ContainsKey (key))
    {
        return allSets[key];
    }
}

private static readonly Dictionary<Type, CustomSet<Type>> allSets = new Dictionary<Type, CustomSet<Type>>()
{
    {typeof(AppLog), AppLogs}
};

public static CustomSet<AppLog> AppLogs { get; set; }

EDIT

code updated so that only the mentioned compilation error will be present


Solution

  • You'd need your appSets dictionary to be less type-safe to achieve that. Define it as Dictionary<Type, object> and cast the item back to CustomSet<TEntity> after retrieving:

    private static readonly Dictionary<Type, object> allSets = new Dictionary<Type, object>.Add(typeof(AppLog), AppLogs);
    
    public CustomSet<TEntity> Set<TEntity>() where TEntity : class
    {
        Type key = typeof (TEntity);       
    
        if (allSets.ContainsKey(key))
        {
            return (CustomSet<TEntity>)allSets[key];
        }
    }