Suspicious Type Conversion

ID

csharp.suspicious_type_conversion

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

CSharp

Tags

casting, reliability

Description

Reports explicit cast expressions between unrelated types — specifically casts between a numeric type and string. Such casts compile only because the developer asked for an unchecked conversion, but they throw InvalidCastException at runtime.

Rationale

(int) someString and (string) someInt do not parse or stringify their operand; they attempt a reference cast. string is not a numeric type and is unrelated to the numeric primitives in the inheritance hierarchy, so the cast cannot succeed for any non-null value. The fix is almost always int.Parse(…​) or value.ToString().

public class Demo
{
    public int Parse(string text)
    {
        return (int) text;                              // FLAW - throws at runtime
    }

    public string Render(int n)
    {
        return (string) (object) n;                     // FLAW
    }

    public int ParseOk(string text) => int.Parse(text); // OK

    public string RenderOk(int n) => n.ToString();      // OK

    public double Widen(int n) => (double) n;           // OK - numeric widening
}

Remediation

Use the appropriate conversion API: int.Parse(…​) / int.TryParse(…​) to turn a string into a number, and value.ToString() (or string.Format/interpolation) to turn a number into a string. If a cast is truly intended (e.g. between numeric types), the rule is silent because such conversions are legal.