rspec/rules/S1858/csharp/rule.adoc

37 lines
1.0 KiB
Plaintext
Raw Normal View History

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:
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
== 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
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 12:47:33 +02:00
----
var v = string.Format("{0}", 1.ToString());
----