1

I get an error whenever I try to add a new a object to my model I get this error "Object reference not set to an instance of an object." Not sure why as I always create a new object.

I have a Model which consist of:

public class Model
{
    public IList<Model1> Something { get; set; }
    public IList<Model2> Something1 { get; set; }
}

I also have in my controller:

        Model model = new Model();

        HttpCookie cookie = Request.Cookies["Login"];
        if (cookie != null)
        {
            int ID = int.Parse(cookie["ID"]);

            var DBInfo = db.Details(ID);
            foreach (var info in DBInfo)
            {
                Something1 model1 = new Something1();
                model1.ID = ID;
                model1.FullName = info.FullName;
                model1.CourseCode = info.CourseCode;
                model.Something1.Add(model1);

            }

The error pops up when I am adding this model1 to model

tereško
  • 56,151
  • 24
  • 92
  • 147
user1938460
  • 75
  • 1
  • 1
  • 9
  • Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Dec 15 '13 at 13:29
  • I did see that but coudln't unserstand why my code made the error as I thought I was creating a new object using this line "Something1 model1 = new Something1();", but it seems I have to create a new list to add the object which is something I did not realise. – user1938460 Dec 15 '13 at 13:33

1 Answers1

4

You must initialize Something1 field before use, like this:

model.Something1 = new List<Model2>();

Or, when init Model:

Model model = new Model
{
    Something = new List<Model1>(),
    Something1 = new List<Model2>()
};
Boris Parfenenkov
  • 2,893
  • 1
  • 21
  • 30