@(at) sign in file path/string

Possible Duplicate:
What’s the @ in front of a string for .NET?

I have the following code:

new Attachment(Request.PhysicalApplicationPath + @"pdf" + pdfItem.Value)

What does the @ sign do?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

It has nothing to do with filepath. It changes the escaping behavior of strings.

In a string literal prefixed with @ the escape sequences starting with are disabled. This is convenient for filepaths since is the path separator and you don’t want it to start an escape sequence.

In a normal string you would have to escape into \ so your example would look like this “pdf\”. But since it’s prefixed with @ the only character that needs escaping is " (which is escaped as "") and the can simply appear.

This feature is convenient for strings literals containing such as filepaths or regexes.

For your simple example the gain isn’t that big, but image you have a full path "C:\ABC\CDE\DEF" then @"C:ABCCDEDEF" looks a lot nicer.

For regular expressions it’s almost a must. A regex typically contains several escaping other characters already and often becomes almost unreadable if you need to escape them.

Method 2

It’s a verbatim string literal.

This allows the string to contain backslashes and even linebreaks without them being handled differently:

string multiLineString = @"First line
second line
third line";

As backslashes aren’t used for escaping, inserting a double quote into the string requires it to be doubled:
string withQuote = @"before""after";

Verbatim string literals are typically used for file paths (as you’ve shown) and regular expressions, both of which frequently use backslashes.

See my article on strings for more information.

Method 3

It allows you to enter the backslash () without escaping it:

 var s1 = "C:\Temp\MyFileName";
 var s2 = @"C:TempMyFileName";

Both result in a string with the same contents (and since strings are interned at compile time, probably even the same string reference).


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x