David Bandel David Bandel - 3 months ago 13
C# Question

Self referential class

Trying to write a class for a directory which can have a parent and a list of children.

Class definition:

class Directory {
public string name;
public Directory parentDir;
public List<Directory> subDirs;

public Directory(string name) {
this.name = name;
}

public void addSubDir(Directory x) {
subDirs.Add(x);
}
}


Sample code trying to create two instances and set one as a child of the other:

Directory temp1 = new Directory("root");

Directory temp2 = new Directory("games");

temp1.addSubDir(temp2);


The error I get is:

System.NullReferenceException was unhandled
Message=Object reference not set to an instance of an object.

Answer

You never instantiated this

public List<Directory> subDirs;

Change it to this:

public List<Directory> subDirs = new List<Directory>();

Since you put it in your title, I thought I would comment. Your error doesn't have anything to do with being a self referential class (it's perfectly fine to do that). If it was an error with being able to do that, you would get a compile time error and not a run time one.