| Property | Value |
|---|---|
| Package | Philips.CodeAnalysis.MaintainabilityAnalyzers |
| Diagnostic ID | PH2146 |
| Category | Maintainability |
| Analyzer | AvoidToStringOnStringAnalyzer |
| CodeFix | Yes |
| Severity | Info |
| Enabled By Default | Yes |
Calling ToString() on an expression that is already of type string is redundant and should be removed to improve code clarity and performance.
Remove the unnecessary .ToString() call from string expressions.
Code that triggers a diagnostic:
class BadExample
{
public void BadMethod()
{
string str = "hello";
string result = str.ToString(); // Redundant
System.Console.WriteLine("world".ToString()); // Redundant
string combined = (str + " world").ToString(); // Redundant
}
}And the replacement code:
class GoodExample
{
public void GoodMethod()
{
string str = "hello";
string result = str; // ToString() removed
System.Console.WriteLine("world"); // ToString() removed
string combined = (str + " world"); // ToString() removed
}
}Note: The analyzer only flags ToString() calls with no parameters. Calls like str.ToString(CultureInfo.InvariantCulture) are not flagged as they may have different behavior.
This analyzer does not offer any special configuration. The general ways of suppressing diagnostics apply.