Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does `@` mean at the start of a string in C#?

Tags:

string

c#

Consider the following line:

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

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

like image 496
Sungguk Lim Avatar asked Apr 14 '10 23:04

Sungguk Lim


2 Answers

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

like image 64
MikeP Avatar answered Oct 20 '22 21:10

MikeP


@ 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";
like image 30
Billy ONeal Avatar answered Oct 20 '22 19:10

Billy ONeal