skjcyber
skjcyber

Reputation: 5957

How can I dispose an object

I am trying to delete a Node from a linked list. Below is the code I have tried.

public class Node : IDisposable
{
    public int Value { get; set; }
    public Node Next { get; set; }

    public Node(int value)
    {
        this.Value = value;
    }

    public void Dispose()
    {
        Dispose(true);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            Next.Dispose();
        }
    }
}

public class LinkedList
{
    Node head;
    public void CreateList()
    {
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);

        head = node1;
        node1.Next = node2;
        node2.Next = node3;
    }

    public void DeleteLastItem()
    {
            Node prevNode = head;
            Node nextNode = head;

            while (nextNode.Next != null)
            {
                prevNode = nextNode;
                nextNode = nextNode.Next;
            }
            prevNode.Next = null;
            nextNode.Dispose();
    }
}

I wanted to dispose the nextNode (which is nothing but the last node. And it will not be part of the Linked List).

When I try above code, I am getting below exception:

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.

How can I proceed here ? How can I dispose a Node object?

Upvotes: 2

Views: 591

Answers (3)

Dan Pichelman
Dan Pichelman

Reputation: 2332

In your Dispose logic, check for NULL:

public class Node : IDisposable
{
    public int Value { get; set; }
    public Node Next { get; set; }

    public Node(int value)
    {
        this.Value = value;
    }

    public void Dispose()
    {
        Dispose(true);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (Next != null) // <-- new code here
            {
                Next.Dispose();
            }                 
        }
    }
}

Upvotes: 1

Marshall777
Marshall777

Reputation: 1204

I guess you should simply check if Next is not null before calling Dispose on it.

When the Dispose method is called on any node, you manually call the next one so one you will reach the last one, the Next property will be null therefore you get this exception.

Considering the code you gave, I don't see why you would need your node to be disposable. It is only necessary if you use non managed resources which is not the case in the code you gave (but maybe you simplified it for the question).

Upvotes: 3

Guffa
Guffa

Reputation: 700342

In your Dispose(bool) method, you can only dispose the next node if there is one. Check for a null reference before you attempt that:

protected virtual void Dispose(bool disposing) {
  if (disposing) {
    if (Next != null) {
      Next.Dispose();
    }
  }
}

Upvotes: 4

Related Questions