CodeQL documentation

Useless upcast

ID: cs/useless-upcast
Kind: problem
Severity: warning
Precision: medium
Tags:
   - maintainability
   - language-features
   - external/cwe/cwe-561
Query suites:
   - csharp-security-and-quality.qls

Click to see the query in the CodeQL repository

In most situations, casting an expression where there exists a corresponding implicit conversion serves no purpose.

Recommendation

Remove the redundant cast.

Example

In this example, casting explicitly from Sub to Super is redundant.

class Bad
{
    class Super {}
    class Sub : Super {}

    void M()
    {
        var sub = new Sub();
        Super super = (Super)sub;
    }
}

The code above can be fixed, either by removing the explicit cast, or by making super an implicitly typed (var) variable.

References