In a method I yield a custom object which I reuse. later for yielding again.
private IEnumerable<DistributorMonthlyComparisonData> ExtractMonthlyAggregate(String CSVFilepath)
{
DistributorMonthlyComparisonData unitData = new DistributorMonthlyComparisonData();
while (!reader.EndOfStream)
{
if(something){
// fill unitData
}
else{
yield return unitData;
}
}
}
In another object in my program I call said method in this way:
List<DistributorMonthlyComparisonData> distribList = new List<DistributorMonthlyComparisonData>();
foreach (DistributorMonthlyComparisonData result in ExtractMonthlyAggregate(percorso))
{
distribList.Add(result);
}
If I don’t create in the yielding method, after each yield, a new object
unitData = new DistributorMonthlyComparisonData();
All I get is a List of identical objects.
I am wondering: is this because unitData is being passed as a reference and thus the List is merely a List of references to the same identical object? Creating a new unitData() every time changes the hash of the unitData object being passed?
Please enlighten me. 🙂
EDIT I am interested in why this is happening.
I used to think that the framework is supposed to do copy-on-write on objects, so basically yielding one object then modifying its properties and then yielding it again should result in two different objects being added to the list.
C# has reference semantics for class types, so you are right about references being returned.
Sidenote about the rest:
yield return/yield breakwill continue the loop you place them in. Therefore, the code before your loop is only executed once before the loop is entered. You would have tonewyour returned objects inside the loop.I.e., you would have to replace
with