Unhelpful "Invert 'if' statement to reduce nesting" inspection

Given the following code:

IEnumerable<String> GetStrings(Boolean flag) {

  if (flag) {

    yield return "Foo";

    yield return "Bar";

  }

}

ReSharper 5.1 will suggest to invert 'if' statement to reduce nesting. However, in this particular case the refactoring does not reduce nesting at all. The refactored code:

IEnumerable<String> GetStrings(Boolean flag) {

  if (!flag) {} else {

    yield return "Foo";

    yield return "Bar";

  }

}

It may be a small detail, but apparently ReSharper is clever enough to generate correct albeit more complex code so it should be possible to simply avoid suggesting the inspection in that particular case.

3 comments
Comment actions Permalink

I noticed this behavior too.

In this case the expected result for me is

IEnumerable<String>  GetStrings(Boolean flag) {

  if (!flag) {

    return;

  }
  yield return "Foo";

  yield return "Bar";  

}

0
Comment actions Permalink

sheitmann wrote:

I noticed this behavior too.

In this case the expected result for me is

IEnumerable<String>  GetStrings(Boolean flag) {

  if (!flag) {

    return;

  }
  yield return "Foo";

  yield return "Bar";  

}

That code will not compile. In the body of the if statement you will either have to return an IEnumerable<String> or use yield return or yield break. I haven't seen ReSharper generate code that doesn't compile.

0
Comment actions Permalink

fixed :) (i hope)

IEnumerable<String>   GetStrings(Boolean flag) {

   if (!flag) {

    yield break;

  }
   yield return "Foo";

   yield return "Bar";  

}

Liversage wrote:

That code will not compile. In the body of the if statement you will either have to return an IEnumerable<String> or use yield return or yield break. I haven't seen ReSharper generate code that doesn't compile.

it was my expected result, not what resharper is doing actually.

0

Please sign in to leave a comment.