implementing the generic interface

Posted by user845405 on Stack Overflow See other posts from Stack Overflow or by user845405
Published on 2014-06-06T15:18:36Z Indexed on 2014/06/06 15:24 UTC
Read the original article Hit count: 160

Filed under:
|
|
|
|

Could any one help me on implementing the generic interface for this class. I want to be able to use the below Cache class methods through an interface.

Thank you for the help!.

public  class CacheStore
{
    private  Dictionary<string, object> _cache;
    private  object _sync;

    public CacheStore()
    {
        _cache = new Dictionary<string, object>();
        _sync = new object();
    }

    public  bool Exists<T>(string key) where T : class
    {
        Type type = typeof(T);

        lock (_sync)
        {
            return _cache.ContainsKey(type.Name + key);
        }
    }

    public  bool Exists<T>() where T : class
    {
        Type type = typeof(T);

        lock (_sync)
        {
            return _cache.ContainsKey(type.Name);
        }
    }

    public  T Get<T>(string key) where T : class
    {
        Type type = typeof(T);

        lock (_sync)
        {
            if (_cache.ContainsKey(key + type.Name) == false)
                throw new ApplicationException(String.Format("An object with key '{0}' does not exists", key));

            lock (_sync)
            {
                return (T)_cache[key + type.Name];
            }
        }
    }

    public  void Add<T>(string key, T value)
    {
        Type type = typeof(T);

        if (value.GetType() != type)
            throw new ApplicationException(String.Format("The type of value passed to 
            cache {0} does not match the cache type {1} for key {2}",     
            value.GetType().FullName, type.FullName, key));

        lock (_sync)
        {
            if (_cache.ContainsKey(key + type.Name))
                throw new ApplicationException(String.Format("An object with key '{0}'  
                already exists", key));

            lock (_sync)
            {
                _cache.Add(key + type.Name, value);
            }
        }
    }
}

Could any one help me on implementing the generic interface for this class. I want to be able to use the below Cache class methods through an interface.

© Stack Overflow or respective owner

Related posts about c#

Related posts about ASP.NET