I have a collection of objects entering a method as an IEnumerable of which I am grouping them by a reference property and then processing them group by group. The processing involves mutating the other properties of the objects. When the method completes and returns, the caller expects to have the collection of objects it passed in to be mutated. The whole process is asynchronous and the method looks like the following:
public async Task MutateMyObjects(IEnumerable<MyObjects> myObjects,
CancellationToken cancellationToken)
{
var myObjectsGroupedByGroupingEntity = myObjects
.GroupBy(myObject => myObject.GroupingEntity);
foreach (var myObjectGroup in myObjectsGroupedByGroupingEntity )
{
await ProcessGroup(myObjectGroup.Key, myObjectGroup, cancellationToken);
}
}
Both MyObject and GroupingEntity are classes, as such my expectation is that MyObjects are passed as reference types and mutation is inherent through the process.
What actually happens is the caller of MutateMyObjects observes the same property values of MyObjects as it observed before the method call. These results are observed after the Task completes. While debugging the method above, observing the variable states before the method returns shows that the object collection under the variable myObjectGroup contain the mutated properties while the object collection under the variable myObjects does not.
I'm not sure what aspect of my understanding is missing causing me to get the wrong expectation, any insights would be greatly appreciated.
someList.Select(x => new MyObjects(x))then each time you iterated it will create new objects. You can pass it to theMutateMyObjectsand it will mutate the objects it creates, but if you iterated theIEnumerableagain it will create brand new unmutated objects.IEnumerable<MyObjects>perhaps hitting your database again for new data?