2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-01-27 13:42:22 +01:00
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.
2020-06-30 12:47:33 +02:00
2021-02-02 15:02:10 +01:00
2021-01-27 13:42:22 +01:00
This rule raises an issue when ``++ToString()++`` is invoked:
2020-06-30 14:49:38 +02:00
2021-01-27 13:42:22 +01:00
* on a ``++string++``
* on a non-``++string++`` operand to concatenation
* on an argument to ``++string.Format++``
2020-06-30 12:47:33 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2020-06-30 12:47:33 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2020-06-30 12:47:33 +02:00
----
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
----
2023-05-03 11:06:20 +02:00
=== Compliant solution
2020-06-30 12:47:33 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2020-06-30 12:47:33 +02:00
----
var s = "foo";
var t = "fee fie foe " + s;
var someObject = new object();
var u = "" + someObject;
var v = string.Format("{0}", someObject);
----
2023-05-03 11:06:20 +02:00
=== Exceptions
2020-06-30 12:47:33 +02:00
2021-01-27 13:42:22 +01:00
The rule does not report on value types, where leaving off the ``++ToString()++`` call would result in automatic boxing.
2020-06-30 14:49:38 +02:00
2023-05-25 14:18:12 +02:00
[source,csharp]
2020-06-30 12:47:33 +02:00
----
var v = string.Format("{0}", 1.ToString());
----
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-09-20 15:38:42 +02:00
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
* There's no need to call "ToString()" on a string.
* There's no need to call "ToString()", the compiler will do it for you.
2021-09-20 15:38:42 +02:00
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== on 11 Dec 2015, 09:11:10 Tamas Vajk wrote:
\[~ann.campbell.2] LGTM
=== on 15 Jan 2016, 14:22:14 Ann Campbell wrote:
\[~dinesh.bolkensteyn] the title you changed was carefully negotiated with [~tamas.vajk]
include::../comments-and-links.adoc[]
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]