Monday, June 05, 2006

C# String Literals and the '@' Character

Specifying Windows file paths in C# code can result in some messy-looking string literals, due to the need to specify "\\" as each backslash character to avoid having a single backslash character be interpreted as the beginning of an escape sequence. For example:

string myAppPath = "C:\\Program Files\\MyApp";

(For the purposes of this post, I'm ignoring the fact that assuming that "myApp" will always be located at "C:\Program Files\" may not be a good idea.)

A way to make this look cleaner (and possibly be less confusing) is to use a '@' character prior to the string literal. The '@' character makes C# skip looking for any escape characters in the string (with the exception of the \" escape sequence). This use of the '@' character before a string literal is called a verbatim string literal. The file path declaration above, revised to use a verbatim string literal, would be:

string myAppPath = @"C:\Program Files\MyApp";

For more details on verbatim string literals, see the string literals page in the C# Language Specification.

Also, the Visual Studio IDE supports displaying verbatim string literals in a different color than standard string literals, for further clarity. I have my Visual Studio installations configured to display standard string literals in off-white and verbatim string literals in red.

No comments:

Post a Comment

Hi spammers! No need to waste your time here; comments are heavily moderated, so if you like, you can save us both a little time and just move on to the next site. :-)

For everyone else: Thanks for visiting! Your comments are more than welcome!