I'm trying to create a list and insert values in to it. But when I add a new item it changes all existing items in the list to the same value I add and I don't understand why.
Here is my code:
public List<Times> CreateListOfTimes()
{
var listOfTimes = new List<Times>();
var times = new Times();
int startTime = 8;
int endTime = startTime + 1;
for (int i = 0; i < 8; i++)
{
times.StartTime = startTime;
times.EndTime = endTime;
listOfTimes.Add(times);
startTime++;
endTime++;
}
return listOfTimes;
}
The first time I add a value to times, times.StartTime = 8 and times.EndTime = 9. When I loop the second time I add 9 and 10 but i also change the already added 8 and 9 to 9 and 10. Why does it happen and how can I fix it?