Search code examples
c#exceptiongetnullreferenceexceptionactionresult

C# object reference not set to an instance of an object in IHttpActionResult


I have had some problems with my code giving a nullreferenceexception. But i don't understand why. In the code below my program gives me a nullrefexc.

The second code part is the variable which the 'var models' should represent. I also tried using the second part code but it also says the same if I use the variable favorites in the IHttpActionResult code.

Exception:

            public IHttpActionResult GetAllFavorites()
            {
                var models = _favoriteModelFactory.CreateFavoritesFromFavoriteModel(_favoriteRepository.GetAll(),
                    _favoriteRepository);
                return Ok(models);
            }

Second part:

        public IEnumerable<Favorite> GetAll()
    {
        IEnumerable<Favorite> favorites = new List<Favorite>
        {
            new Favorite
            {
                StudentId = 1,
                FavoritesIds = {2,5,8},
                FavoriteId = 1
            }
        };
        return favorites;         
    }

Thanks for helping!


Solution

  • Assuming "FavoritesIds" is a List.. It is never instantiated in your code snippet. So when you assign {2,5,8} to it, you get null reference exception.

    You can solve this in two ways.

    1. In Favourite class constructor

    2. In GetAll() Method

      public static IEnumerable<Favorite> GetAll()
              {
                  IEnumerable<Favorite> favorites = new List<Favorite>()
              {
                  new Favorite
                  {
                      StudentId = 1,
                      FavoritesIds = new List<int> {2,5,8},
                      FavoriteId = 1
                  }
              };
                  return favorites;
              }    
      

    OR

    public class Favorite
        {
            public Favorite()
            {
                FavoritesIds = new List<int>();
            }
            public int StudentId { get; set; }
            public List<int> FavoritesIds { get; set; }
            public int FavoriteId { get; set; }
        }