Arian Kulp's Blog
opinion, insight, and occasional code

Escaping

Tuesday, July 25, 2006 9:45 AM
No, I'm not trying to get away!  I was working in C# last night and learned some new things related to string escaping.  We all know about \n (carriage return) and \t (tab), but did you know about the @ (at) sign?

If you place the "at" in front of a string, you can use backslashes without doubling them.  As an example, if you wanted to reference a file path in code, you would typically need:

string path = "c:\\Path\\OtherPath\\File.ext";

This is tedious, so MS decided to allow you to avoid that.  Instead you can use:

string path = @"C:\Path\OtherPath\File.ext";

Pretty nice looking.  Really, it's best suited for paths.  When you have the "at" sign, you can't use \n, \t, or (and this part was new to me) quotes.  Typically, quotes are escaped as slash-quote.  Since slashes lose their escaping quality in literal strings, you must double the string:

string val = @"I said, ""These are quotes"" to everyone.";

That's kind of ugly, but then again, so are slash-quotes.  I think VB handles quote escaping that way anyway.  The weirdest thing though, was carriage returns.  If you need to insert a carriage return in a literal string, slashes are meaningless.  What you actually end up doing, is literally adding a carriage return:

string longString = @"So I had a first line
a second line ""with quotes ""
and a third line with some \backslashes\.";

Now that's weird!  You can make some seriously strange looking code that way.  Of course, the code editor colors it as quoted, but in Notepad or some other editor, it may not look right.  I think I'll avoid literal strings in the future, except for file paths.  They just look too strange to me!
Comments have been closed on this topic.