Search code examples
c#yield-return

Why does next statement after yield return get executed?


I have the following function that iterates some rows and searches for files in a database. A null gets returned by the repository if file is not found in the database and the function should then return an empty ResultRow. The Assert() after the if statement fires in some cases. Why? How is that possible?

IEnumerable<ResultRow> DoRows(SequenceListWithQc list, 
IList<TestSpecification> testSpecs, bool writeResults=false)
{
    foreach (var row in list.Rows)
    {
        var result = new ResultRow();

        result.FileName = row.Columns[list.Headers.IndexOf("File Name")];

        var rawFile = repository.GetRawFileByFilename(result.FileName);

        if (rawFile == null)
        {
            yield return result;
        }

        Debug.Assert(rawFile != null);
    }
}

Solution

  • You can call continue to move onto the next row in the loop

        if (rawFile == null)
        {
            yield return result;
            continue;
        }