0

I have same type of 2 object lists and first item of first list should be added specific times. Also every cycle i should increase the datetime value with AddSeconds(). This is my code below:

List<Logs> logList = new List<Logs>();
List<Logs> chartList = new List<Logs>();

for (int i = 0; i < specificValue; i++)
{
    chartList.Add(logList[0]);
    logList[0].Date = logList[0].Date.AddSeconds(1);                    
}

My purpose is creating chart data with change log so i have to add same value to chartList with specific time with incremental date value. But my problem this code creates a chartList with all the same value of the last loglist item. I found some solutions with using foreach but in that situation i have to use for loop.

diiN__________
  • 7,393
  • 6
  • 42
  • 69
CanESER
  • 301
  • 1
  • 3
  • 19

1 Answers1

2

When you call chartList.Add(logList[0]), you are adding a reference to the object, not creating a new object.

So on the next line, when you add 1 second to the object, you also add that 1 second to the object in chartList. In fact, all the objects in chartList are references to the exact same object.

You need to create a copy of the object when you add it to chartList.

Eli
  • 693
  • 5
  • 12
  • if you mean this, I have tried also Logs log = new Logs(); log = logList[0]; log.Date = log.Date .AddSeconds(1); chartList.Add(log); Can you explain me that on the code? – CanESER Jun 23 '16 at 12:51
  • For emphasis, the important part here is "are references to the exact same object". Read [this](http://stackoverflow.com/questions/5057267/what-is-the-difference-between-a-reference-type-and-value-type-in-c) for more information. – DonBoitnott Jun 23 '16 at 12:52
  • 1
    @CanESER As soon as you do `log = logList[0];`, you are making the variable a reference to logList[0], and the new object you created with `log = new Logs()` will go to the garbage collector. You need to make an actual copy. One way would be to create a copy constructor in the Logs class, then create the new object with `Logs log = new Logs(logList[0])`; – Eli Jun 23 '16 at 13:06
  • @Eli u are my hero! I was trying to fix that problem since morning. I realized i know so less about objects. But now everything is well with ur help. Thank you so much – CanESER Jun 23 '16 at 13:30
  • @CanESER My pleasure :) – Eli Jun 23 '16 at 13:41