Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 425
Vaibhav Jain Avatar asked May 26 '11 06:05

Vaibhav Jain


People also ask

Is char * A string literal?

String literals are convertible and assignable to non-const char* or wchar_t* in order to be compatible with C, where string literals are of types char[N] and wchar_t[N]. Such implicit conversion is deprecated.

What are string literals used for?

In practice, a string literal lets you set specific strings as a type. In the example above, I have a person interface with a name , age , and mood . Name and age use prototypes, but mood uses a string literal. The syntax for creating string literals is similar to union types.

What is prefix in C#?

In this article The @ character prefixes a code element that the compiler is to interpret as an identifier rather than a C# keyword. The following example uses the @ character to define an identifier named for that it uses in a for loop. C# Copy.


2 Answers

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

like image 106
abatishchev Avatar answered Sep 30 '22 11:09

abatishchev


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"; 
like image 21
V4Vendetta Avatar answered Sep 30 '22 10:09

V4Vendetta