Roslyn: Code fix for 'if' statement can be simplied produces incorrect code with yield return

Created on 18 Jun 2018  路  5Comments  路  Source: dotnet/roslyn

```C#
using System;
using System.Collections.Generic;

namespace YieldReturn
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}

    public static IEnumerable<string> GetStrings(int value)
    {
        if (value % 2 == 0)
        {
            yield return "Even";
        }

        yield return "Number";
    }
}

}
```
image

Expected Behavior:
yield return value % 2 == 0 ? "Even" : "Number";
Actual Behavior:
return value % 2 == 0 ? "Even" : "Number";

Version Used:
VS 15.8.0 Preview 3.0 27813.1.d15.8

Area-IDE Bug Resolution-Fixed

All 5 comments

Fascinating. I wonder if this is expected. @mavasani I'm using IOperation here. Is it expected that you get an IReturnOperation for "yield return" statements?

Thanks!

Ah, i see. There are three 'kinds' that you can get with IReturnOperation ('return', 'yieldreturn' and 'yieldbreak'). Should be a simple fix.

Note: there are two 'reasonable' fixes here.

  1. just don't offer the feature. super simple to do if these are IReturnOperations without the right kind.
  2. offer the feature, but intelligently generate yield return ... if both return statements are the yield reutrns.

I would prefer combine if both are yield else no suggestion.

@smitpatel Yup. That's what my PR does. Cheers! :)

Was this page helpful?
0 / 5 - 0 ratings