Search code examples
linked-listnullobject-reference

Linked List - Object reference not set to instance of object


I'm writing a method that adds a new Node to the back of a linked list:

public void add(string title, string director, int year, double cost)
    {
        Node newNode = new Node();
        newNode.disc = new BluRayDisc(title, director, year, cost);

        Node holder = new Node();
        holder = first;
        while (holder.next != null)    //object reference error
        {
            holder = holder.next;
        }
        holder.next = newNode;
    }

but am getting a "System.NullReferenceException: 'Object reference not set to an instance of an object.'" error thrown.

The 'first' node is initialized to null so I'm assuming that's where my problem comes from. This is my first linked list, and this follows the example of an addToBack method I was given exactly. Does anyone have some insight on this problem?


Solution

  • A few issues:

    • first can be null, which is the case when you start with an empty linked list, and in that case first.next is an invalid reference.

    • About: Node holder = new Node();. It is not necessary to create a new node here, with new Node(), since in the next statement, you are throwing away that node, by doing holder = first;

    Here is the correction:

    public void add(string title, string director, int year, double cost)
    {
        Node newNode = new Node();
        newNode.disc = new BluRayDisc(title, director, year, cost);
    
        if (first == null) {
            first = newNode;
            return;
        }
        holder = first;
        while (holder.next != null)    //object reference error
        {
            holder = holder.next;
        }
        holder.next = newNode;
    }