-1

In the below snippet, I made changes to the 'current' object, which is a copy of 'head' object. However, changes get reflected to the global head object.

class Node
    {
        public Node next; //pointer
        public Object data; //data

        public Node(Object d)
        {
            data = d;
        }
    }    

public class CustomLinkedList
        {
            private Node head = new Node(null); //head of linked list

            public void Add(Object data)
            {
                Node newNode = new Node(data);

                Node current = head;

                while (current.next != null)
                {
                    current = current.next;
                }

                current.next = newNode;
            }
    }
Abhishek Poojary
  • 749
  • 9
  • 10

1 Answers1

1

Reason for this is - Classes are reference types.

A reference type is a type which has as its value a reference to the appropriate data rather than the data itself. That's why changing one object changes other as well.

Read these - http://www.yoda.arachsys.com/csharp/parameters.html

http://www.albahari.com/valuevsreftypes.aspx

Solution is to deep clone the object in consideration.

Read this - Deep cloning objects

Abhishek Poojary
  • 749
  • 9
  • 10