-7

I encountered this error: NullReferenceException: Object reference not set to an instance of an object

When creating the countStats object, it is NULL, after which I try to assign a value to the field of this class and get this error. What am I doing wrong?

public async Task<MainPageViewModel> GetMainPageViewModelAsync()
        {
            var model = new MainPageViewModel();
            var countStats = new StatsCountsViewModel(); // NULL

            if (!_cache.TryGetValue("CountsStats", out countStats))
            {
                var result = await _contextRepository.GetStatsMainPageAsync();

                countStats.CountSms = "300"; //ERROR
                countStats.CountUsers = "600";
                countStats.CountSuccessForecast = "1228";

                model.Stats = countStats;

                _cache.Set("CountsStats", countStats, new MemoryCacheEntryOptions
                {
                    AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
                });
            }

            var forecasts = await _contextRepository.GetForecastsOnSaleAsync();

            foreach (var item in forecasts)
            {
                model.Forecasts.Add(item);
                model.Bookmaker.Add(await _contextRepository.GetBookmakersForForecastsAsync(item.Id));
            }

            return model;

        }
 public class StatsCountsViewModel
    {
        public string CountUsers { get; set; }
        public string CountSms { get; set; }
        public string CountSuccessForecast { get; set; }

    }
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
pitten
  • 77
  • 1
  • 10
  • 2
    While good answer by John provides copy-paste ready solution there is really nothing new in your question - code explicitly runs when you get no object from cache and such case (variable initialized with default `null` value) already covered in standard duplicate. – Alexei Levenkov Jan 30 '20 at 06:37

2 Answers2

4

This is your problem:

_cache.TryGetValue("CountsStats", out countStats)

out will change the object that countStats is pointing to. If it's found in the cache, then it will be the cached object. Great! If it isn't, then it will be null. You need to create a new instance in this case.

You should change your code to this:

var countStats = null;

if (!_cache.TryGetValue("CountsStats", out countStats))
{
    countStats = new StatsCountsViewModel();
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
1

The problem is here:

if (!_cache.TryGetValue("CountsStats", out countStats))

You are passing the countStats using the out word, and somewhere in the try get value, you are setting a null in there.

Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61