Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# generic cache with type safe

I'm looking for a way to have a generic local cache for any object. Here is the code :

    private static readonly Dictionary<Type,Dictionary<string,object>> _cache 
        = new Dictionary<Type, Dictionary<string, object>>();

    //The generic parameter allow null values to be cached
    private static void AddToCache<T>(string key, T value)
    {
        if(!_cache.ContainsKey(typeof(T)))
            _cache.Add(typeof(T),new Dictionary<string, object>());

        _cache[typeof (T)][key] = value;
    }

    private static T GetFromCache<T>(string key)
    {
        return (T)_cache[typeof (T)][key];
    }   

1- Is there a way not to cast on the getfromcache method ?

2- Is there a way to ensure type safe in the second dictionnary, say all the object would have the same type. (This is provided by the addToCache method but I would prefer a type control in the design himself). For eg to have _cache of the following type

    Dictionary<Type,Dictionary<string,typeof(type)>>

Thx

like image 391
Toto Avatar asked Feb 27 '26 16:02

Toto


2 Answers

Try this:

static class Helper<T>
{
       internal static readonly Dictionary<string, T> cache = new Dictionary<string, T>();
}
private static void AddToCache<T>(string key, T value)
{
   Helper<T>.cache[key] = value;
}
private static T GetFromCache<T>(string key)
{
    return Helper<T>.cache[key];
}
like image 86
Daniel Avatar answered Mar 01 '26 06:03

Daniel


Why not just put generic parameter to class declaration:

public class Cache<T>
{
    private Dictionary<string, T> _cache = new Dictionary<string, T>();
    ...

}

it can be static if you prefer

like image 25
Dmitry Ornatsky Avatar answered Mar 01 '26 07:03

Dmitry Ornatsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!