What does the @ prefix do on string literals in C#

41,291

Solution 1

@ 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.

Solution 2

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";

Solution 3

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.

Solution 4

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.

Solution 5

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

Share:
41,291
Vaibhav Jain
Author by

Vaibhav Jain

IT professional

Updated on May 28, 2020

Comments

  • Vaibhav Jain
    Vaibhav Jain almost 4 years

    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?