David Bandel David Bandel - 10 months ago 52
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) {

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");


The error I get is:

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


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.