I am trying to search a list and then extract some objects of it put them into another list and write the list to a file.
I think that my code is right but when I execute it I get a NullReference exception. If someone could check my code would I would be really grateful.
Here’s my code for the Search method that I use
public void Search( string day)
{
foreach (Classes c in studentClasses)
{
if (c.Day == day)
{
studentClassesByDay.Add(c);
}
}
}
And that’s the code which adds the new list to a file
private void btnDay_Click(object sender, EventArgs e)
{
SelectDayForm selectDay = new SelectDayForm();
if (selectDay.ShowDialog() == DialogResult.OK)
{
l.Search(selectDay.theDay);
trg.GenerateSortedListReport(l.studentClassesByDay, AppData.byDay);
MessageBox.Show("A list of sorted student classes written to file " + AppData.byDay+ ".");
// txtDay.Text =selectDay.theDay;
}
}
You haven’t shown on which line the exception occurs (which would be handy) but you also haven’t shown where
studentClassesByDayhas been instantiated.That would be the first thing I would check.
The only possibilities in the code you’ve shown are:
lis null;trgis null;l.studentClassesByDayis null; orAppDatais null (though that’s probably not so – it looks like a class).Simply put some debug statements (or breakpoints in your debugger) before each attempted dereference and check the values.
Based on your comment that the errant line is:
it’s almost guaranteed (as suspected) that you havent actually instantiated this variable. I’d look into that.