The requested page is not available for the requested platform. You are viewing the content for Default platform.

Cannot yield in the body of a finally clause

CodeRush Classic shows the Cannot yield in the body of a finally clause code issue if the yield keyword is located within the body of a finally clause.

Fix

Move the yield statement out of the finally clause body.

Purpose

Highlights the yield statements, which would cause the Cannot yield a value in the body of a finally clause compilation error.

Example

public IEnumerable GetFileTexts(string files)
{
    string[] fileNames = files.Split(',');
    string text;
    foreach (string fName in fileNames)
    {
        try
        {
            text = File.ReadAllText(fName);
        }
        finally
        {yield return text;
        }
    }
}

Fix:

public IEnumerable GetFileTexts(string files)
{
    string[] fileNames = files.Split(',');
    string text;
    foreach (string fName in fileNames)
    {
        try
        {
            text = File.ReadAllText(fName);
        }
        finally
        {
        }
        yield return text;
    }
}