0

Im populating a List with my object (Event).
The object has a field called DocumentDate that is what I wish to update in each item. But after the loop, all items in the list are the same! I want to know why:

The code:

private List<Events> CreateEventsBetween(string start, string end, string repeatState, Event defaultEvent)
{
    var states = Resources.GetStringArray(Resource.Array.repeat_states);
    DateTime.TryParse(start, out DateTime dtStart);
    DateTime.TryParse(end, out DateTime dtEnd);
    List<Event> events = new List<Event>();

    if (repeatState == states[0])
        while(dtStart<= dtEnd)
        {
            var e = defaultEvent;
            e.DocumentDate = dtStart;
            events.Add(e);

            dtStart= dtStart.AddDays(i);
        }
    ...
    ...
    ...

    return events;
}

Here every item in the list of events have the same DocumentDate's, when they should have different ones

Erick Santander
  • 311
  • 3
  • 17
  • Instead of the while loop, you could also assign the events in a single line using `System.Linq`, for example: `var events = Enumerable.Range(0, dtEnd.Subtract(dtStart).Days).Select(i => new Event {DocumentDate = dtStart.AddDays(i)}).ToList();` – Rufus L Nov 15 '18 at 17:24
  • Sorry, I corrected the generic List thing, now, I don't think that would do for me, my object has other fields (about 24 or so), and I need the other fields to be equal to the defaultEvent, just changing the DocumentDate. – Erick Santander Nov 16 '18 at 12:32
  • In that case you may need to implement a deep copy method on your class if the goal is to allow callers of this method to define their own default property values. That way you can create a new instance based on the one passed in. [this question](https://stackoverflow.com/questions/78536/deep-cloning-objects) has answers that describe how to implement a deep clone method on a class. – Rufus L Nov 16 '18 at 16:49

1 Answers1

2

Because all events are the same reference. You assign it at var e = defaultEvent;.

Instead you need to initialize different with new:

var e = new Event{ DocumentDate = dtStart }; // other properties as well
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • the date aux was supposed to be dtStart, sorry, I was translating the code to put it in here, and forgot to change that, thanks. I was suspicious about the defaultEvent, but since I changed the date I thought it would mater, anyways, thanks again! – Erick Santander Nov 15 '18 at 17:16