SonarSource/sonar-dotnet

Fix S1944 FP: Rule fails to check for generic types

Opened this issue · 2 comments

Description

Rule S1944: "Invalid casts should be avoided" wrongly claims that there are no types that extend the source and the target of the cast, when working with generic types.

Repro steps

New Console App:

Result<string> error = new Error<string>();
var castedError = (IFailure)error; // <- Review this cast; in this project there's no type that extends 'Result<string>' and implements 'IFailure'.	

public abstract class Result<TData> { }

public interface IFailure { }

public class Error<TData> : Result<TData>, IFailure { }

Case was simplified for reproduction.

Expected behavior

No warning, the cast is fine and doesn't throw an exception.

Actual behavior

Warning.

Known workarounds

Suppress the warning.

Related information

The code that searches for a type that has source and destination type in common needs to consider generics better.
After all, it only asks to review, so that's OK.

  • Dotnet 8
  • Visual Studio 2022 Community
  • SonarAnalyzer.CSharp Version=9.26.0.92422

Thank you for reporting this issue. It's indeed a False Positive.
It won't be easy to fix, as it requires Symbolic Execution (and the rule is listed under Symbol Execution rules but doesn't use the CFG).

It's not a SE rule in the new engine.