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

Non-spammers: Thanks for visiting! Please go ahead and leave a comment; I read them all!

Attention SPAMMERS: I review all comments before they get posted, and I REPORT 100% of spam comments to Google as spam! Why not avoid getting your account banned as quickly -- and save us both a little time -- by skipping this comment form and moving on to the next one on your list? Thanks, and I hope you have a great day!