Search code examples
stringvisual-studio

Zero Width Space character in string literals: Detect and/or prevent


Visual Studio allows the Unicode character Zero Width Space (U+200B) to be pasted into the code editor. This character is (as the name implies) invisible.

This can lead to nasty bugs such as the one I just spent time troubleshooting where HttpWebRequest.CreateHttp(string url) threw a UriFormatException when passed the innocuous-looking string literal "​http://www.umich.edu".

The exception occurred because the first character in that string literal is not h, as it appears, but is the Zero Width Space character. It was put onto the clipboard when I copied the URL from the body of a web page, and was dutifully pasted into my code by Visual Studio when I hit Ctrl+V in the code editor window.

Turning on the "View White Space" option (Edit > Advanced > View White Space) does not cause Visual Studio to reveal that there's a Zero Width Space character present.

I would like Visual Studio to:

  • Give some kind of indication or warning when there's a Zero Width Space character (or other invisible character) in a string literal in my code, and/or
  • Prevent such control characters from being pasted into the code editor in the first place.

Is there a way to make Visual Studio do this?


Solution

  • As of December 2021, Visual Studio Code introduced highlighting of invisible characters.

    From this

    Zero width unicode character error in code

    to this

    Zero width unicode character highlight

    Preferences -> Settings (ctrl + ,) -> search for "invisible characters" -> tick "Editor › Unicode Highlight: Invisible Characters"

    VSC Unicode Highlight: Invisible Characters

    This option should be on by default.