CodeQL documentation

Redundant ToString() call

ID: cs/useless-tostring-call
Kind: problem
Security severity: 
Severity: recommendation
Precision: high
Tags:
   - maintainability
   - useless-code
Query suites:
   - csharp-security-and-quality.qls

Click to see the query in the CodeQL repository

In certain contexts, such as when concatenating a string and an object, calling ToString explicitly can be omitted.

Recommendation

Remove the redundant call to ToString.

Example

In the following example, ToString is called explicitly on o, before being passed to string.Format.

using System;

class Bad
{
    static string Hello(object o)
    {
        return string.Format("Hello, {0}!", o.ToString());
    }
}

In the revised example, the call to ToString is omitted, as string.Format will invoke ToString implicitly.

using System;

class Good
{
    static string Hello(object o)
    {
        return string.Format("Hello, {0}!", o);
    }
}

References

  • © GitHub, Inc.
  • Terms
  • Privacy