Using left double quotation marks in strings in VB

zanhtet picture zanhtet · Jan 12, 2011 · Viewed 10.8k times · Source

In following code, the usage of the string "“" (i.e. a left double quotation mark inside a string) results in a compile error in VB.NET:

StringVar = Replace(StringVar, "“", "“")

What’s going on here?

Answer

Konrad Rudolph picture Konrad Rudolph · Jan 12, 2011

It seems as if you want to replace curly quotes with their HTML code equivalent.

On the first glance, your code is absolutely correct. The problem is that VB allows curly quotes in place of regular quotes in code (because Unicode is great, right?). That is, the following codes are all equivalent:

Dim str = "hello"
Dim str = “hello”
Dim str = "hello“

Now, if you want to use a quotation mark inside a string, VB doesn’t know whether the quotation mark is supposed to end the string or not. In C#, this would be fixed by escaping the quotation mark, i.e. in place of """ you’d write "\"". In VB, the same is done by doubling the quotation mark, i.e. """".

Back to your curly quote. The same as for straight quotes applies according to the VB language specification (¶1.6.4). So to write a curly quote in code, try the following:

StringVar = Replace(StringVar, "““", "“")

Unfortunately, I cannot try this code now and it’s altogether possible that the IDE simply replaces this by straight quotes. If that’s the case, an alternative is to use Chr or ChrW with the character code of the “left double quotation mark”:

StringVar = Replace(StringVar, ChrW(&H201C), "“")

Or, for symmetry, written in decimal (but I prefer hexadecimal for character codes):

StringVar = Replace(StringVar, ChrW(8220), "“")

Something else: the Replace function will probably soon be deprecated and doesn’t work everywhere (e.g. Windows Phone 7). Instead, use the Replace method of the String class:

StringVar = StringVar.Replace(, ChrW(8220), "“")