Skip to content

Do you still ASCII?

From time to time we get code that illustrates a problem a user is having when they rely on old-school ASCII. This problem can occur when using the Chr function to create a character.

One example we see reasonably frequently is code to create a string that contains a quote like:

 dim someString as String = chr(34) + "someValue" + chr(34)

This style is not necessary and may give unwanted results if you have an unusual string encoding. Instead, you can write this without the use of the Chr function. Here’s how:

Simply put 2 quotes inside the string value where you want one to appear like so:

 dim someString as String = """someValue"""

Or create a constant, put one quote in the constant and write it like this:

 dim someString as String = kQuote + "someValue" + kQuote

The other one we see  from time to time is very similar:

 // trying to use "extended ascii" from a list like http://www.asciitable.com
 dim someString as String = chr(179) + "someValue" + chr(179)

This one is subtly worse since Chr returns a valid ASCII character only for values <= 127 and returns the character that is that code point for values > 127. Since your string is actually UTF8, when you use chr(179) you get ³ (a superscript 3) and not the vertical bar you might have expected from the ASCII chart.

You can create a constant for the vertical bar symbol or you can use this code that references a specific TextEncoding where the vertical bar is 179:

 Dim verticalBar As String = Encodings.DOSLatin1.chr(179)

So remember, ASCII is not as commonly used these days.