Why is this an issue?
Non-encoded control characters and whitespace characters are often injected in the source code because of a bad manipulation. They are either
invisible or difficult to recognize, which can result in bugs when the string is not what the developer expects. If you actually need to use a control
character use their encoded version (ex: ASCII \n,\t,
… or Unicode U+000D, U+0009,
…).
This rule raises an issue when the following characters are seen in a literal string:
No issue will be raised on the simple space character. Unicode U+0020
, ASCII 32.
Noncompliant code example
string tabInside = "A B"; // Noncompliant, contains a tabulation
string zeroWidthSpaceInside = "foobar"; // Noncompliant, it contains a U+200B character inside
Console.WriteLine(zeroWidthSpaceInside); // Prints "foo?bar"
Compliant solution
string tabInside = "A\tB"; // Compliant, uses escaped value
string zeroWidthSpaceInside = "foo\u200Bbar"; // Compliant, uses escaped value
Console.WriteLine(zeroWidthSpaceInside); // Prints "foo?bar"
Exceptions
Verbatim string literals have no escape character mechanism.