Reputation: 305
Can anybody suggest what is wrong here?
public class Student
{
public List<Class> Classes { get; set; }
public Student(List<Class> classes)
{
this.Classes = classes;
}
public Student(Class class)
{
//This does not work
//Error: Object reference not set to an instance of an object.
this.Classes.Add(class);
}
}
Calling it as following works
var classes = new List<Classes>();
classes.Add(new Class("English", "Elective"));
classes.Add(new Class("Math", "Core"));
..more classes to add
Student student = new Student(classes);
When I have call like this (only one class to add)
Student student = new Student(new Class("Masters","Accounts"));
I get error. Thank you.
Upvotes: 0
Views: 254
Reputation: 9664
this.Classes is not initialized:
public class Student
{
public List<Class> Classes { get; set; }
public Student(List<Class> classes)
{
this.Classes = classes;
}
public Student(Class class)
{
this.Classes = new List<Class>();
this.Classes.Add(class);
}
}
Upvotes: 2
Reputation: 43067
Your overload with Class needs to initialize Classes before adding class. Try this:
public class Student
{
public List<Class> Classes { get; set; }
public Student(List<Class> classes)
{
this.Classes = classes;
}
public Student(Class class)
{
this.Classes = new List<Class>();
this.Classes.Add(class);
}
}
Upvotes: 6
Reputation: 32258
You need to initalize Classes
before attempting to add an object to it.
Upvotes: 0