Search code examples
c#.netdictionarynullreferenceexception

Dictionary TryGetValue NullReferenceException


I am getting NullReferenceException at the _dicCache.TryGetValue(objID, out newObject); line. And I have no Idea why this is happening at all. Can comeone point me to the right direction please?

Here is my class:

public class Cache<T>
{
    public string Name { get; set; }

    private  Dictionary<int, T> _dicCache = new Dictionary<int, T>();

    public  void Insert(int objID, T obj)
    {
        try
        {
            _dicCache.Add(objID, obj);

            HttpContext.Current.Cache.Insert(Name, _dicCache, null, DateTime.Now.AddMinutes(10), TimeSpan.FromMinutes(0));
        }
        catch (Exception)
        {
            throw;
        }
    }

    public bool Get(int objID, out T obj)
    {
        _dicCache = (Dictionary<int, T>)HttpContext.Current.Cache.Get(Name);


        try
        {
            return _dicCache.TryGetValue(objID, out obj);
        }
        catch (Exception)
        {
            throw;
        }
    }
 }

And here is how I call it:

   Services.Cache<Entities.User> cache = new Services.Cache<Entities.User>();
   cache.Name = Enum.Cache.Names.usercache.ToString();


   Entities.User user = new Entities.User();

   cache.Get(pUserId, out user);

I Also have tried to change to Get class to:

    public T Get(int objID, out T obj)
    {
        _dicCache = (Dictionary<int, T>)HttpContext.Current.Cache.Get(Name);

        T newObject = (T)Activator.CreateInstance<T>();


        try
        {
            _dicCache.TryGetValue(objID, out newObject);

            obj = newObject;

            return obj;
        }
        catch (Exception)
        {
            throw;
        }
    }

But I still get the same NullReferenceException at the _dicCache.TryGetValue(objID, out newObject); line.


Solution

  • I think the only way you could have that exception is if your dictionary is null.

    _dicCache.TryGetValue(objID, out newObject);
    

    null is not a valid argument for the key (if TKey is a reference type), though in your case it's int so cannot be null. You'd see an ArgumentNullException if passing a null value for key anyway.

    Are you sure _dicCache is not null? I would check the value of the assignment:

    _dicCache = (Dictionary<int, T>)HttpContext.Current.Cache.Get(Name);