-3

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.
David Bandel
  • 201
  • 1
  • 15
  • forget to initialize subDirs . `public List subDirs = new List();` :) – L.B Aug 30 '16 at 19:28
  • Please explain how these questions are duplicates. I'm asking what I was doing wrong with having a class contain a member that is a pointer to its same type. And the problem was that I wasn't initializing that member. The other question is much more abstract and wouldn't come up in a search for my specific problem at all. They are so far removed I can't tell if this is just a joke or a troll. – David Bandel Sep 01 '16 at 14:18
  • Basically I'm asking for a solution to problem X, which gives error Y. And the other question is about error Y. There are many problems that could result in error Y. – David Bandel Sep 01 '16 at 14:20

1 Answers1

2

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.

kemiller2002
  • 107,653
  • 27
  • 187
  • 244