tags:

views:

162

answers:

3

Consider the following line:

readonly private string TARGET_BTN_IMG_URL = @"\\ad1-sunglim\Test\";

In this line, why does @ need to be attached?

+10  A: 

It denotes a literal string, in which the '\' character does not indicate an escape sequence.

MikeP
"You could to double each backslash with same effect: `TARGET_BTN_IMG_URL = "\\\\ad1-sunglim\\Test\\";`"
Rubens Farias
Yeah, but it is not as easy to read, which is why this option exists.
Ed Swangren
sunglim
+2  A: 

because you string contains escape sequence "\". in order to tell compiler not to treat "\" as escape sequence you have to use "@".

Nnp
+6  A: 

@ tells C# to treat that as a literal string verbatim string literal. For example:

string s = "C:\Windows\Myfile.txt";

is an error because \W and \M are not valid escape sequences. You need to write it this way instead:

string s = "C:\\Windows\\Myfile.txt";

To make it clearer, you can use a literal string, which does not recognize \ as a special character. Hence:

string s = @"C:\Windows\Myfile.txt";

is perfectly okay.


EDIT: MSDN provides these examples:

string a = "hello, world";                  // hello, world
string b = @"hello, world";                 // hello, world
string c = "hello \t world";                // hello     world
string d = @"hello \t world";               // hello \t world
string e = "Joe said \"Hello\" to me";      // Joe said "Hello" to me
string f = @"Joe said ""Hello"" to me";     // Joe said "Hello" to me
string g = "\\\\server\\share\\file.txt";   // \\server\share\file.txt
string h = @"\\server\share\file.txt";      // \\server\share\file.txt
string i = "one\r\ntwo\r\nthree";
string j = @"one
two
three";
Billy ONeal
It's worth noting the specific case of wanting to put a quote `"` in a verbatim string. This is possible using double quote marks `""`. This can be seen in the `@"Joe said ""Hello"" to me"` example above).
Lawrence Johnston
String literals can also notably span multiple lines...
Noldorin
Offtopic: Where did that "verbatim" prefix originated?
OscarRyz
@Oscar Reyes: Err.. because that's what Eric Lippert + friends decided to use when they designed C#?
Billy ONeal
@Noldorin: *Normal* string literals can't span multiple lines. *Verbatim* string literals can span multiple lines.
Billy ONeal
@Billy I meant, why are they called `verbatim` what's the origin the *verbatim* word ( aside from the company with that name )
OscarRyz
@Oscar Reyes: The word `verbatim` is standard English. ( http://en.wiktionary.org/wiki/verbatim ) It means "literally" or "exactly" or "word-for-word". For example, "The student copied the teacher's notes verbatim."
Billy ONeal
@Billy Oh I see, I thought it was one of those slangs with obscure origin, thanks.
OscarRyz
@Billy: Yeah, you know what I mean. :)
Noldorin