6

I want to wrap List class with my custom class. As for now I have something like this ;

public class PriorityListOfNodes
{

    private List<Node>          list_;
    private IComparer<Node>     sorter_;

    public List<Node> List_ {
            get {return list_;}
            set {list_ = value;}
    }

    public PriorityListOfNodes ()
    {
            sorter_ = new NodeSorter_fValueDescending ();
    }

    public Node PopFromEnd ()
    {
            Node temp = new Node (list_ [list_.Count - 1]);
            list_.RemoveAt (list_.Count - 1);
            return temp;
    }

    public Node PeekFromEnd ()
    {
            return list_ [list_.Count - 1];
    }

    public void Add (ref Node toAdd)
    {
            Debug.Log (toAdd);
            list_.Add (toAdd);
            list_.Sort (sorter_);
    }
}

When I do now

Node temp = new Node(10,20); //custom constructor
PriorityListOfNodes l = new PriorityListOfNodes();
l.add(temp); 

I get runtime exception :

Object reference not set to an instance of an object

I have also tried without ref but with the same result. What am I doing wrong here ?

Patryk
  • 22,602
  • 44
  • 128
  • 244

2 Answers2

10

You never actually instantiate a List<Node>.

 public PriorityListOfNodes ()
    {
            sorter_ = new NodeSorter_fValueDescending ();
            list_ = new List<Node>();
    }
Pete
  • 10,651
  • 9
  • 52
  • 74
1

By default, classes have empty parameterless constructors, so you effectively have:

public class PriorityListOfNodes
{
    private List<Node> list_;
    // ...

    public PriorityListOfNodes()
    {
    }

    // ...
}

When you later call Add your list is declared, but not initialised. You need to do this at some point, probably in the constructor:

public class PriorityListOfNodes
{
    private List<Node> list_;
    // ...

    public PriorityListOfNodes()
    {
         this.list_ = new List<Node>();
         // ...
    }

    // ...
}

See Using Constructors (C#).

RichardTowers
  • 4,682
  • 1
  • 26
  • 43