SonarSource / sonar-dotnet

Code analyzer for C# and VB.NET projects
https://redirect.sonarsource.com/plugins/csharp.html
GNU Lesser General Public License v3.0
797 stars 229 forks source link

Fix S5034 FP: `ValueTask.IsCompletedSuccessfully` not considered in ternary operator #9661

Open fiotti opened 2 months ago

fiotti commented 2 months ago

Description

S5034 does not take ternary operators into consideration.

Repro steps

class Test
{
  static ValueTask<IEnumerable> MakeGeneric(ValueTask<IEnumerable<T>> task)
    => task.IsCompletedSuccessfully
      // S5034: Refactor this 'ValueTask' usage to consume the result only if the operation has completed successfully.
      ? ValueTask.FromResult<IEnumerable>(task.Result)
      : MakeGenericSlow(task);

  static async ValueTask<IEnumerable> MakeGenericSlow(ValueTask<IEnumerable<T>> task)
    => await task;
}

Expected behavior

No warning.

Actual behavior

S5034: Refactor this 'ValueTask' usage to consume the result only if the operation has completed successfully.

Known workarounds

class Test
{
  static ValueTask<IEnumerable> MakeGeneric(ValueTask<IEnumerable<T>> task)
  {
    if (task.IsCompletedSuccessfully)
      return ValueTask.FromResult<IEnumerable>(task.Result); // No warning.

    return MakeGenericSlow(task);
  }

  static async ValueTask<IEnumerable> MakeGenericSlow(ValueTask<IEnumerable<T>> task)
    => await task;
}

Related information

mary-georgiou-sonarsource commented 2 months ago

Hello @fiotti I confirm this is a false positive. Thank you for reporting this.