peacefulmember
peacefulmember

Reputation: 305

Constructor overload

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

Answers (4)

Aaron Daniels
Aaron Daniels

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

jrummell
jrummell

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

SLaks
SLaks

Reputation: 887195

In the second constructor, you never initialized Classes

Upvotes: 3

George Johnston
George Johnston

Reputation: 32258

You need to initalize Classes before attempting to add an object to it.

Upvotes: 0

Related Questions