What does the @ prefix do on string literals in C#
I read some C# article to combine a path using Path.Combine
(part1,part2).
It uses the following:
string part1 = @"c:\temp";
string part2 = @"assembly.txt";
May I know what is the use of @
in part1 and part2?
@
is not related to any method.
It means that you don't need to escape special characters in the string following to the symbol:
@"c:\temp"
is equal to
"c:\\temp"
Such string is called 'verbatim' or @-quoted. See MSDN.
As other have said its one way so that you don't need to escape special characters and very useful in specifying file paths.
string s1 =@"C:\MyFolder\Blue.jpg";
One more usage is when you have large strings and want it to be displayed across multiple lines rather than a long one.
string s2 =@"This could be very large string something like a Select query
which you would want to be shown spanning across multiple lines
rather than scrolling to the right and see what it all reads up";
As stated in C# Language Specification 4.0:
2.4.4.5 String literals
C# supports two forms of string literals: regular string literals and verbatim string literals. A regular string literal consists of zero or more characters enclosed in double quotes, as in "hello", and may include both simple escape sequences (such as \t for the tab character), and hexadecimal and Unicode escape sequences. A verbatim string literal consists of an @ character followed by a double-quote character, zero or more characters, and a closing double-quote character. A simple example is @"hello". In a verbatim string literal, the characters between the delimiters are interpreted verbatim, the only exception being a quote-escape-sequence. In particular, simple escape sequences, and hexadecimal and Unicode escape sequences are not processed in verbatim string literals.
It denotes a verbatim string literal, and allows you to use certain characters that normally have special meaning, for example \
, which is normally an escape character, and new lines. For this reason it's very useful when dealing with Windows paths.
Without using @
, the first line of your example would have to be:
string part1 = "c:\\temp";
More information here.
With @ you dont have to escape special characters.
So you would have to write "c:\\temp" without @
If more presise it is called 'verbatim' strings. You could read here about it:
http://msdn.microsoft.com/en-us/library/aa691090(v=vs.71).aspx