@ sign?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I saw the following line of sourcecode:
string input = @"the quick brown fox jumped over the lazy dog";

What is the purpose of the '@' above? I tried running with and without and
get seemingly same results. Anyone know?
 
That string will be the same with or without the '@'. The '@'
eliminates escape chars by telling the compiler that it is a verbatim
string. This makes writing stuff like file paths easier.

@"c:\stuff.txt" represents just what it says, however "c:\stuff.txt"
will give a compile error because it is trying to find a special char
related to \s.

MessageBox.Show("Hello\nWorld")
gives:

Hello
World

MessageBox.Show(@"Hello\nWorld")
gives:

Hello\nWorld

I would not suggest using it when it is not needed.

HTH,
Dan
 
@ is used when you want to assign a file path to a string.

ex:

string strFilePath = @"C:/MyDir/thisFile.txt"

if you are not using @, you got to assign it as

string strFilePath = "C://MyDir//thisFile.txt"

-Lalasa.
 
This is true because "\\" is a special character interpreted as literal
"\".

Another very important use is when dealing with regex. You want regex
to interpret "\w" as a word character, not make the compiler puke
trying to figure out what it means. You don't want to write confusing
and ugly regex statements where all of the "\" characters are doubled.

HTH,
Dan
 
It also lets you embed a return in a string, for example:

string stuff = @"hello
there, how are
you?";
 
That is a quoted string literal.

The advantage of @-quoting is that escape sequences are not processed,
which makes it easy to write, for example, a fully qualified file name:
@"c:\Docs\Source\a.txt" // rather than "c:\\Docs\\Source\\a.txt"
(http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html
/vclrfString.asp)

The reason you don't see a difference in your example is because your
string does not have any escape sequences.

Cheers,
Christian T. [MSFT]
Visual Studio Update Team

- Please do not reply to this email directly. This email is for newsgroup
purposes only.
=========================================================================
This posting is provided "AS IS" with no warranties, and confers no
rights. Use of included script samples are subject to the terms specified
at http://www.microsoft.com/info/cpyright.htm

Note: For the benefit of the community-at-large, all responses to this
message are best directed to the newsgroup/thread from which
they originated.
=========================================================================

--------------------
 
It also allows you to use reserved words as variable names.

public void Foo(string @string)
{
// ...
}
 
Thanks to everyone who responded to this question. Your answers were all very
clear and helpful. Cheers...

-Ben
 
Back
Top