S1858 — "ToString()" calls should not be redundant

Language
C#
Type
Code smell
Severity
Minor
Tags
finding, clumsy

Why is this an issue?

Invoking a method designed to return a string representation of an object which is already a string is a waste of keystrokes. Similarly, explicitly invoking ToString() when the compiler would do it implicitly is also needless code-bloat.

This rule raises an issue when ToString() is invoked:

Noncompliant code example


var s = "foo";
var t = "fee fie foe " + s.ToString();  // Noncompliant
var someObject = new object();
var u = "" + someObject.ToString(); // Noncompliant
var v = string.Format("{0}", someObject.ToString()); // Noncompliant

Compliant solution


var s = "foo";
var t = "fee fie foe " + s;
var someObject = new object();
var u = "" + someObject;
var v = string.Format("{0}", someObject);

Exceptions

The rule does not report on value types, where leaving off the ToString() call would result in automatic boxing.


var v = string.Format("{0}", 1.ToString());

↑ Back to top