But how can you check if the Title property has changed? Are you calling GetObjectsFromApiCall() again? Or are you foreach again through the same instance of objects ?
An IEnumerable instance can create and create new objects each time they are "listed." So, here is a simple example to illustrate. In this example, define:
class SomeObject { public string Title { get; set; } }
Then we look at two types of "source", first an array, and then an iterator block, defined as follows:
static IEnumerable<SomeObject> GetSomeSequence() { yield return new SomeObject { Title = "Alpha", }; yield return new SomeObject { Title = "Beta", }; yield return new SomeObject { Title = "Gamma", }; }
Then check it as follows:
static void Main() { IEnumerable<SomeObject> thingsToModify; // set source to an array thingsToModify = new[] { new SomeObject { Title = "Alpha", }, new SomeObject { Title = "Beta", }, new SomeObject { Title = "Gamma", }, }; foreach (var t in thingsToModify) Console.WriteLine(t.Title); foreach (var t in thingsToModify) t.Title = "Changed!"; foreach (var t in thingsToModify) Console.WriteLine(t.Title); // OK, modified // set source to something which yields new object each time a new GetEnumerator() call is made thingsToModify = GetSomeSequence(); foreach (var t in thingsToModify) Console.WriteLine(t.Title); foreach (var t in thingsToModify) t.Title = "Changed!"; // no-one keeps these modified objects foreach (var t in thingsToModify) Console.WriteLine(t.Title); // new objects, titles not modified }
Conclusion: it is quite possible to change the state of a mutable object that belongs to the source that we iterate. But some types of IEnumerable sources give new copies of the data every time they are called, and then it is useless to make changes to the copy.
source share