Search code examples
c#static-membersgeneric-collections

Use generic type as a static member of base class


I have a static member in the base class of type:

private static Dictionary<string, IEnumerable<T>> cachedList;    

This generic member should be available in all derived classes. I'm not sure how to solve it.

EDIT
change member to protected, does not cure my problem.
for more clarification, I used this line of code

    public static void Cache(bool cached)
    {
        string value = typeof(T).ToString();

        if (cachedList == null)
            cachedList = new Dictionary<string, IEnumerable<T>>();
        ///some other things
    }

But every derived class has their own copy of cachedList and every classes returns "true" for the statement of cachedList == null


Solution

  • Are you asking how to create a static member of a generic class which is shared across all specializations (i.e. all values of T)? If so, read on:

    You can't do this directly, however you could add an extra base class that your base class inherits from:

    public class NonGenericBase
    {
        private static Dictionary<string, IEnumerable<object>> cachedList = new Dictionary<string, IEnumerable<object>>();
    
        protected static IEnumerable<T> GetCachedList<T>(string key) {
            return (IEnumerable<T>)cachedList[key];
        }
    
        protected static void SetCachedList<T>(string key, IEnumerable<T> value)
            where T : class
        {
            cachedList[key] = (IEnumerable<object>)value;
        }
    }
    

    And then wrap the usage of GetCachedList and SetCachedList in the generic derived class.