yeehsienq
yeehsienq

Reputation: 3

How to add elements into a LinkedList without them changing during compilation

I'm writing a C# code on Visual Studio. I've created a LinkedList<"T"> (called 'data') and a temporary variable of type T (lets call it 'temp'). the variable properties of temp always changes during compilation, and at certain junctions, I add it to the list as follows.
data.addLast(temp);
I originally expect data to have a list of different values, but it only captures multiple copies of the final value of temp. I don't intend to change the variable data to an array. How can I get the list to produce values in the way I expect it to?

Edit: Alright, I apologize in advance for sounding a bit too abstract but here goes
`

public class Obj { 
    public String name; 
} 

and here's my main class:

   LinkedList<Obj> data = new LinkedList<Module>(); 
    Obj temp = new Obj(); 
    temp.name = "ABC"; 
    data.AddLast(temp); 
    temp.name = "DEF"; 
    data.AddLast(temp); 

`

When I print the name property for each element in data, both produce "DEF". I can't understand as to why though.

Upvotes: 0

Views: 51

Answers (1)

Adem Catamak
Adem Catamak

Reputation: 2009

You have to copy object and modified that if you want to not affect original object. Class objects are reference typed so, - MyClass temp = originalObject; - temp and originalObject actually point to the same memory address. Hence; It does not matter changing temp or originalObject property.

I code small example according to your case, I hope it helps.

class Program
{
   public class Obj
   {
       public String name;

       public Obj Clone()
       {
           return this.MemberwiseClone() as Obj;
       }
   }
   static void Main(string[] args)
   {
       LinkedList<Obj> data = new LinkedList<Obj>();
       Obj temp = new Obj();
       temp.name = "ABC";
       data.AddLast(temp);
       Obj tempCopy = temp.Clone();
       tempCopy.name = "DEF";
       data.AddLast(tempCopy);

       foreach (Obj myClass in data)
       {
           Console.WriteLine(myClass.name);
       }

       Console.ReadKey();
   }
}

Upvotes: 1

Related Questions