-1

I keep getting an unhandled exception

"Object reference not set to an instance of an object"

for the following code, specifically on the line temp.next = node. Can anyone help me figure out why?

The code below is a class for birds where the user inputs a name and the addBird method is suppose to add the name to the end of the linked list.

 class BirdsSurve    {

    private Node first;

    public class Node
    {
        public string Name { get; set; }
        public  int count { get; set; }
        public Node next;

        public Node()
        {


            this.count = 1;


        }

        public void setNext(Node Next)
        {

            next = Next;

        }
        public int addCount()
        {
             count++;
            return count;
        }
    }
    public BirdsSurvey()
    {
        this.first = null;

    }
    public void addBird(string bird)
    {
        Node node = new Node();
        node.Name = bird;
        if (first == null)
        { first = node; }
        else
        {
           Node temp = first;
            while (temp != null)
            {
                if (temp.Name == bird)
                { temp.addCount(); }


                if (temp.next == null)
                {
                    temp = temp.next;
                    temp.next = node; }
               // temp = temp.next;
            }
        }
    }
codeLover
  • 2,402
  • 1
  • 8
  • 21
Ace
  • 1
  • 1
  • 2
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Llama Oct 29 '18 at 02:52
  • 1
    `if (temp.next == null)` -> if temp.next **IS** null, `temp = temp.next;` set temp to temp's next (i.e. set temp to `null`), and then `temp.next = node;` try to access a property of the `null` value. – Llama Oct 29 '18 at 02:54
  • 1
    Comment out `temp = temp.next;` It should not be there. – mjwills Oct 29 '18 at 02:56
  • `I tried setting the setting temp to null` **No-one** suggested you do that. Have another read of my earlier suggestion. – mjwills Oct 29 '18 at 03:12
  • @Ace consider `temp = null; temp.next = node;` - how can you access `.next` if `temp` is null? – Llama Oct 29 '18 at 03:46

1 Answers1

2

You set temp to temp.next within the if clause, which checks, if temp.next is null. So, you basically set temp to be null. So, you get the error, because you try to get a next property from a variable, which is null and not an object.

As a side note, maybe rethink the naming of your variables, so that they are not all the same, because that can become confusing quite fast.

Geshode
  • 2,498
  • 5
  • 15
  • 24