NullReferenceException when returning an object in C#, without accessing its parameters

86 Views Asked by At

I haven't programmed in c# in ages, but I have this task for school, where I am supposed to implement a doubly linked list. I am meant to do this, without using OOP, so it is all written procedural. The issue is, whenever I run the code, during the second insertion, at the end, when it should return the node we inserted the new node after, I get a null refference exception.

The whole message is: "System.NullReferenceException: 'Object reference not set to an instance of an object.' node was null."

I have no Idea why this is happening, so I thought I'd post the question here. From the debugger, I can clearly see that node is, in fact, not null, and even if it was, I am just returning the object, not accessing it's properties.

Here is my code:

class Program
{
 
    public class LinkedList
    {
        public int value;
        public LinkedList next;
        public LinkedList prev;
    }

    public static LinkedList CreateLinkedList(int value)
    {
        LinkedList seznam = new LinkedList();
        seznam.value = value;
        seznam.prev = null;
        seznam.next = null;
        return seznam;
    }
    public static LinkedList GetFront(LinkedList node)
    {
        if (node.prev == null)
        {
            return node;
        }
        return GetFront(node.prev);
    }

    public static LinkedList InsertAfter(LinkedList node, int value)
    {

        if (node != null)
        {

            var temp = node.next;
            var newNode = CreateLinkedList(value);
            newNode.prev = node;
            newNode.next = temp;
            node.next = newNode;
            temp.prev = newNode;

            return node;
        }
        return CreateLinkedList(value);

    }

    static void Main(string[] args)
    {
        LinkedList s = null;
        s = InsertAfter(s, 5);
   
        s = InsertAfter(s, 7);
      
    }
}

Any Ideas on what I might be doing wrong? Thanks in advance for the tips, and I hope my mistake wasn't too stupid, lol.

1

There are 1 best solutions below

4
Serge On

sine node.next is null, your temp variable is null too. You have to use ref keyword if you want to assign a temp value a node.next value, after node.next was assigned again

      var temp = node.next; // before
     ref var temp = ref node.next; //should be