Note that there are some explanatory texts on larger screens.

plurals
  1. POYield keyword behavior in C# 2.0
    primarykey
    data
    text
    <p>In a method I yield a custom object which I reuse. later for yielding again. </p> <pre><code>private IEnumerable&lt;DistributorMonthlyComparisonData&gt; ExtractMonthlyAggregate(String CSVFilepath) { DistributorMonthlyComparisonData unitData = new DistributorMonthlyComparisonData(); while (!reader.EndOfStream) { if(something){ // fill unitData } else{ yield return unitData; } } } </code></pre> <p>In another object in my program I call said method in this way:</p> <pre><code>List&lt;DistributorMonthlyComparisonData&gt; distribList = new List&lt;DistributorMonthlyComparisonData&gt;(); foreach (DistributorMonthlyComparisonData result in ExtractMonthlyAggregate(percorso)) { distribList.Add(result); } </code></pre> <p>If I don't create in the yielding method, after each yield, a new object</p> <pre><code>unitData = new DistributorMonthlyComparisonData(); </code></pre> <p>All I get is a List of identical objects.</p> <p>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?</p> <p>Please enlighten me. :)</p> <p><strong>EDIT</strong> I am interested in <em>why</em> 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.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload