views:

95

answers:

4

While searching on how to escape a single quote in String.Format, I found the answer at SO: Escaping single quote in String.Format()

It seems to be different for VB though. I tested it, and indeed C# needs

string s = DateTime.Now.ToString("MMM d \\'yy 'at' H:mmm");

while VB needs

Dim s As String = Now.ToString("MMM d \'yy 'at' H:mmm")

Why does C# need a double backslash, and VB a single backslash? This might be a bit of a silly question to C# users, but while I can read C#, I'm not used to writing it.

+4  A: 

In C#, string literals can contain escape sequences such as \n for a new line or \t for a tab or \" for a quote. If you do not need the escaping, you can prefix the literal with @ (eg: @"MMM ...") and get the same string a VB.

In VB, escaping is never allowed, so there is no need to escape the backslash.

Gideon Engelberth
+1  A: 

The reason why is that C# supports escape sequences within string literals via the \ character. VB has no such escaping mechanisms and hence the single \ is interpretted as a \.

In C# you can get the same behavior by using verbatim strings

@"MMM d \'yy 'at' H:mmm"
JaredPar
+1  A: 

In C# the backslash has a meaning (\n is newline \t tab ....). So backlslahs itselft is an escape character - which you have to escape :) Or place a AT-sign in front of the string - this makes a "non escaped string" (typically used for paths)

ManniAT
+1  A: 

In c# \ will escape . Your text will become "MMM d \'yy 'at' H:mmm". You don't need to escape the ' character in a string. If you were to use " in the string on the other hand, you would need to escape it to not end your string "MMM d \"yy \"at\" H:mmm". Or you could also use the @"" string method which will automatically escape characters for you (not " though). So you could write @"this will not \n be two lines"

simendsjo