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
756 stars 223 forks source link

Fix S1944 FP: Rule fails to check for generic types #9374

Open mtsfoni opened 1 month ago

mtsfoni commented 1 month ago

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.

zsolt-kolbay-sonarsource commented 1 month ago

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).

pavel-mikula-sonarsource commented 1 month ago

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