Use of default ToString()¶
ID: cs/call-to-object-tostringKind: problemSecurity severity: Severity: warningPrecision: very-highTags: - quality - reliability - correctnessQuery suites: - csharp-security-and-quality.qls
Click to see the query in the CodeQL repository
CallingSystem.Object’s (orSystem.ValueType’s)ToString method on a value returns the fully qualified name of the type of that value. In most cases this is not useful, or what was intended. This rule finds explicit and implicit calls to the defaultToString methods.
Recommendation¶
Override the defaultToString method, if possible, or perform bespoke string conversion.
Example¶
In the following example, the defaultToString method is invoked first on an object of typePerson, and then on an integer array. The output results arep:Bad+Person andints:System.Int32[], respectively.
usingSystem;classBad{staticvoidMain(string[]args){varp=newPerson("Eric Arthur Blair");Console.WriteLine("p: "+p);varints=newint[]{1,2,3};Console.WriteLine("ints: "+ints);}classPerson{privatestringName;publicPerson(stringname){this.Name=name;}}}
In the fixed example, theToString method is overridden in the classPerson, andstring.Join is used to print the elements of the integer array (it is not possible to overrideToString in that case). The output results arep:EricArthurBlair andints:1,2,3, respectively.
usingSystem;classGood{staticvoidMain(string[]args){varp=newPerson("Eric Arthur Blair");Console.WriteLine("p: "+p);varints=newint[]{1,2,3};Console.WriteLine("ints: "+string.Join(", ",ints));}classPerson{privatestringName;publicPerson(stringname){this.Name=name;}publicoverridestringToString()=>Name;}}