Skip to content

Latest commit

 

History

History
59 lines (44 loc) · 1.86 KB

File metadata and controls

59 lines (44 loc) · 1.86 KB

PH2146: Avoid calling ToString() on string type

Property Value
Package Philips.CodeAnalysis.MaintainabilityAnalyzers
Diagnostic ID PH2146
Category Maintainability
Analyzer AvoidToStringOnStringAnalyzer
CodeFix Yes
Severity Info
Enabled By Default Yes

Introduction

Calling ToString() on an expression that is already of type string is redundant and should be removed to improve code clarity and performance.

How to solve

Remove the unnecessary .ToString() call from string expressions.

Example

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.

Configuration

This analyzer does not offer any special configuration. The general ways of suppressing diagnostics apply.