0

Possible Duplicate:
What is a NullReferenceException in .NET?

I have a Model (ASP.NET MVC 4, C#) Called HoursOfOperation:

public class HoursOfOperation
{
    public List<DayTimes> Monday { get; set; }
    public List<DayTimes> Tuesday { get; set; }
    public List<DayTimes> Wednesday { get; set; }
    public List<DayTimes> Thursday { get; set; }
    public List<DayTimes> Friday { get; set; }
    public List<DayTimes> Saturday { get; set; }
    public List<DayTimes> Sunday { get; set; }
}

and a DayTimes

public class DayTimes
{
    public int Status { get; set; }
    public string From { get; set; }
    public string To { get; set; }
}

now I'm trying to add a new set to the Monday entity like below:

var _vm = new HoursOfOperation();

_vm.Monday.Add(new DayTimes{
      From = day.From.ToString(),
      To = day.To.ToString(),
      Status = (int)day.Status
});

as soon as the above statement is excecuted I'm getting a "Object reference not set to an instance of an object." Exception

Now I have checked and day.From.ToString() has a "08:00:00", day.To.ToString() has "09:30:00" and day.Status has a 1 at the time at which this statement throws the exception.

Any Ideas?

Community
  • 1
  • 1
hjavaher
  • 2,499
  • 3
  • 27
  • 51
  • 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 Jan 18 '13 at 03:07

4 Answers4

5

That's because Monday is not instantiated.

You should do something like

_vm.Monday = new List<DayTimes>();

or alternatively, make all instantiations in HoursOfOperation's constructor like so:

public HoursOfOperation()
{
   Monday = new List<DayTimes>(),
   Tuesday = new List<DayTimes>(),
   Wednesday = new List<DayTimes>(),
   Thursday = new List<DayTimes>(),
   Friday = new List<DayTimes>(),
   Saturday = new List<DayTimes>(),
   Sunday = new List<DayTimes>()
};
Ofer Zelig
  • 15,893
  • 7
  • 52
  • 89
  • Wow, I'm very new to C# and OOP but I actually knew that and missed it. Thank you, and Thank you all for your response. – hjavaher Jan 18 '13 at 03:15
2

Your lists are null at this point. So

_vm.Monday

..will throw an exception. You have to new them up in the constructor:

public HoursOfOperation() {
    Monday = new List<DayTimes>();
    // ...etc
}
Simon Whitehead
  • 57,414
  • 7
  • 93
  • 127
0

The various List properties are not being initialised; you need to add

_vm.Monday = new List<DayTime>();
RJ Lohan
  • 6,257
  • 3
  • 30
  • 52
0

You need to create instances of the lists of day times:

var hoursOfOperation = new HoursOfOperation
{
   Monday = new List<DayTimes>(),
   Tuesday = new List<DayTimes>(),
   Wednesday = new List<DayTimes>(),
   Thursday = new List<DayTimes>(),
   Friday = new List<DayTimes>(),
   Saturday = new List<DayTimes>(),
   Sunday = new List<DayTimes>()
};
ajawad987
  • 3,990
  • 2
  • 26
  • 42