Samuel J Samuel J - 9 months ago 84
C# Question

C# 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

Answer Source

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
{
    if (allSets.ContainsKey(TEntity))
    {
        return (CustomSet<TEntity>)allSets[TEntity];
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download