Object reference not set to an instance of an object.  MemoryCache.Default.Get(guidToken) as ResponseObject;

yguyon28
yguyon28 used Ask the Experts™
on
I'm getting the following error on my objResponse set to null:

Object reference not set to an instance of an object.... This

var searchCriteria = objResponse.Model as InvoicePrintingParameters;  My objresponse is set to null



       private void AddEmailedCustomersToCacheObject(string guidToken, List<int> emailedCustomers)
        {
            var objResponse = MemoryCache.Default.Get(guidToken) as ResponseObject;
            var searchCriteria = objResponse.Model as InvoicePrintingParameters;

            searchCriteria.listEmailedCustomers = emailedCustomers;

            ResponseObject result = new ResponseObject() { Success = objResponse.Success, Message = objResponse.Message, Model = searchCriteria };
            MemoryCache.Default.Remove(guidToken);
            MemoryCache.Default.Add(guidToken, result, DateTime.Now.AddMinutes(1));
        }

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Chinmay PatelChief Technology Ninja
Distinguished Expert 2018

Commented:
As per the design of the ObjectCache, if the item with a given key is not found it will return null. Are you sure that item exists in the cache?

Author

Commented:
I think what I'm trying to do is if the memory cache is null is to write a better logic than what I have created.
Chief Technology Ninja
Distinguished Expert 2018
Commented:
Something like this? because if
            var objResponse = MemoryCache.Default.Get(guidToken) as ResponseObject;

Open in new window

for some reason then can not proceed further.

       private void AddEmailedCustomersToCacheObject(string guidToken, List<int> emailedCustomers)
        {
            var objResponse = MemoryCache.Default.Get(guidToken) as ResponseObject;
if(objResponse == null )
{
// handle the issue
// you might return; from here or do something else, maybe log the exception - if that is the case.
}else
{
            var searchCriteria = objResponse.Model as InvoicePrintingParameters;

            searchCriteria.listEmailedCustomers = emailedCustomers;

            ResponseObject result = new ResponseObject() { Success = objResponse.Success, Message = objResponse.Message, Model = searchCriteria };
            MemoryCache.Default.Remove(guidToken);
            MemoryCache.Default.Add(guidToken, result, DateTime.Now.AddMinutes(1));
}
        }

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial