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:

    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;
    }