743

This is a .NET question for C# (or possibly VB.net), but I am trying to figure out what's the difference between the following declarations:

string hello = "hello";

vs.

string hello_alias = @"hello";

Printing out on the console makes no difference, the length properties are the same.

Himanshu
  • 31,810
  • 31
  • 111
  • 133
Klaw
  • 7,519
  • 3
  • 18
  • 11
  • Please see (and upvote) my suggestion for the Visual Studio IDE for better verbatim string formatting: [Indent multi-line verbatim strings](https://developercommunity.visualstudio.com/idea/602807/indent-multi-line-verbatim-strings.html). – Olivier Jacot-Descombes Aug 12 '19 at 13:18
  • To be clear, the examples above are producing exactly the same result with or without `@`. – Miro J. Oct 29 '19 at 16:11

9 Answers9

943

It marks the string as a verbatim string literal - anything in the string that would normally be interpreted as an escape sequence is ignored.

So "C:\\Users\\Rich" is the same as @"C:\Users\Rich"

There is one exception: an escape sequence is needed for the double quote. To escape a double quote, you need to put two double quotes in a row. For instance, @"""" evaluates to ".

Richard Ev
  • 52,939
  • 59
  • 191
  • 278
  • 1
    @RichardEverett I understood the answer,But my doubt is what is the actual use of this feature? – Arun Jun 28 '14 at 14:32
  • 39
    @Arun It's really useful when dealing with strings containing things like regular expression definitions that often need things to be escaped themselves – James Thorpe May 22 '15 at 14:40
  • 32
    + multi-line contents – Jaider Sep 01 '15 at 20:49
  • 6
    you also will still have to double up braces `{{` if you want to use a regular brace in a `string.Format` call. – Dave Cousineau Mar 11 '16 at 16:40
  • 5
    @RichardEverett its very useful for creating multi line string literals without having to break the line into pieces. – John Mott Apr 03 '17 at 15:54
  • 1
    Also very useful for VERY long SQL database queries that join a multitude of tables with `INNER` and `OUTER JOIN`s, a plethora of column names and doing conditional `WHERE`s. It makes the string entirely more legible. – Chris Nov 21 '17 at 17:19
  • 1
    So in other languages, this is like triple quotes (`'''` or `"""`) in Python, `[[` and `]]` in Lua, `#"` and `"#` in Rust, ``< – Chromium Jul 17 '18 at 02:48
  • 1
    Seems like your last example is a bit off, what I used is `""` (double quote) which translated into a single quote `"` - but in your example there are 4 quotes. – Yoav Feuerstein Jun 24 '19 at 13:36
  • Combined with string interpolation, a C# 7 feature, my life is complete `var string = $@"This works over multiple` `lines` `and it is everything I hoped it would be {VARABILENAME}";` – Cyrus Downey Nov 12 '19 at 20:11
295

It's a verbatim string literal. It means that escaping isn't applied. For instance:

string verbatim = @"foo\bar";
string regular = "foo\\bar";

Here verbatim and regular have the same contents.

It also allows multi-line contents - which can be very handy for SQL:

string select = @"
SELECT Foo
FROM Bar
WHERE Name='Baz'";

The one bit of escaping which is necessary for verbatim string literals is to get a double quote (") which you do by doubling it:

string verbatim = @"He said, ""Would you like some coffee?"" and left.";
string regular = "He said, \"Would you like some coffee?\" and left.";
l'L'l
  • 44,951
  • 10
  • 95
  • 146
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
74

An '@' has another meaning as well: putting it in front of a variable declaration allows you to use reserved keywords as variable names.

For example:

string @class = "something";
int @object = 1;

I've only found one or two legitimate uses for this. Mainly in ASP.NET MVC when you want to do something like this:

<%= Html.ActionLink("Text", "Action", "Controller", null, new { @class = "some_css_class" })%>

Which would produce an HTML link like:

<a href="/Controller/Action" class="some_css_class">Text</a>

Otherwise you would have to use 'Class', which isn't a reserved keyword but the uppercase 'C' does not follow HTML standards and just doesn't look right.

JulianR
  • 16,213
  • 5
  • 55
  • 85
19

Since you explicitly asked for VB as well, let me just add that this verbatim string syntax doesn't exist in VB, only in C#. Rather, all strings are verbatim in VB (except for the fact that they cannot contain line breaks, unlike C# verbatim strings):

Dim path = "C:\My\Path"
Dim message = "She said, ""Hello, beautiful world."""

Escape sequences don't exist in VB (except for the doubling of the quote character, like in C# verbatim strings) which makes a few things more complicated. For example, to write the following code in VB you need to use concatenation (or any of the other ways to construct a string)

string x = "Foo\nbar";

In VB this would be written as follows:

Dim x = "Foo" & Environment.NewLine & "bar"

(& is the VB string concatenation operator. + could equally be used.)

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 2
    Oh my, that sounds annoying... even more glad I'm using C# now :p – Svish Feb 17 '09 at 11:15
  • You cannot embed line breaks into VB string literals, even though you can into C#'s verbatim string literals. They're thus not the same. – Joey May 03 '11 at 09:15
  • @Svish, Wait am I missing something? This is not a con for VB at all. Indeed this is one place where VB wins C#. It's better to do it this way and explicitly concat the newlines and special characters instead of throwing all the special characters between the `"` and `"`. – Pacerier Apr 06 '15 at 13:53
  • @Pacerier That’s nonsense. As soon as you do more than trivial string processing, proper string building facilities are indispensable, and the ability of concisely handling special characters are foremost amongst these. However, both C# and VB have `String.Format`, which allows doing this. In fact, I would now **never** write `"x" & Environment.NewLine`, and instead *always* use `String.Format("x{0}", Environment.Newline)` etc. Still, C# is more convenient here. – Konrad Rudolph Apr 06 '15 at 15:55
  • @KonradRudolph, I'd choose `"x" & nl & nl` or `"x" + nl + nl` or `"x" . $nl . $nl` any day over `"x\n\n"`. Also `"x" + bs + bs ` over `"x\\\\"`. And `"x" + q + q` over `"x\"\""` / `"x"""""`. Now as for `String.Format`, that's another issue unrelated to the comparison we are doing above. – Pacerier Apr 06 '15 at 17:03
  • @Pacerier Can you articulate *why*, though? It’s longer, and it’s certainly not any clearer — both simply take getting used to. – Konrad Rudolph Apr 06 '15 at 17:53
  • @KonradRudolph, Yes, ease-on-the-eyes is the reason. I'll always sacrifice typing speed (much to spare) for clarity. When I see something like `"x\"\\"\\\""` my eyes have to go through the chars one-by-one, while I can speed read over `"x" + q + q + backslash + q` (oh wait did I insert an extra `\͏` above up there?). Also, `"this\nis\nnot\none\nline"` is too cram and hard to scan over as opposed to `"this" + nl + "is" + nl + "not" + nl + "one" + nl + "line"` (placed on 5 actual lines). – Pacerier Apr 07 '15 at 13:18
  • @Pacerier “ease-on-the-eyes is the reason” — But The C# way is much easier on the eyes, once you get used to it. Hence why I said “it’s certainly not any clearer”. In particular, your code examples are an unfair comparison, since you cannot simply say `"x" + q + nl + backslash + q` in VB. You’d say, for instance, `"x""" & Environment.Newline & "\"""`. Tell me again why this is easier on the eye than `"x\"\n\\\""`. – Konrad Rudolph Apr 07 '15 at 14:11
  • How cumbersome! – Anomaly Apr 11 '23 at 19:16
12

http://msdn.microsoft.com/en-us/library/aa691090.aspx

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. A verbatim string literal may span multiple lines.

Ed Guiness
  • 34,602
  • 16
  • 110
  • 145
11

This is a verbatim string, and changes the escaping rules - the only character that is now escaped is ", escaped to "". This is especially useful for file paths and regex:

var path = @"c:\some\location";
var tsql = @"SELECT *
            FROM FOO
            WHERE Bar = 1";
var escaped = @"a "" b";

etc

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
9

Putting a @ in front of a string enables you to use special characters such as a backslash or double-quotes without having to use special codes or escape characters.

So you can write:

string path = @"C:\My path\";

instead of:

string path = "C:\\My path\\";
senshin
  • 10,022
  • 7
  • 46
  • 59
Presidenten
  • 6,327
  • 11
  • 45
  • 55
9

Copied from MSDN:

At compile time, verbatim strings are converted to ordinary strings with all the same escape sequences. Therefore, if you view a verbatim string in the debugger watch window, you will see the escape characters that were added by the compiler, not the verbatim version from your source code. For example, the verbatim string @"C:\files.txt" will appear in the watch window as "C:\\files.txt".

Joey
  • 344,408
  • 85
  • 689
  • 683
aanund
  • 1,483
  • 11
  • 18
  • Which is a typical misleading piece of Microsoft documentation, IMHO! What the above states as the end result is correct, but the underlying truth is that strings in C# are converted to the relevant sequence of bytes (or multi-byte character codes). C# allows two different ways to represent the underlying string, with @"..." or "...". The debugger always chooses the "..." way, and cannot tell which was used in the first place. (Escape sequences such as \n or "" are only relevant to programming and display level string representation, and are never stored in the underlying string!) – MikeBeaton Jun 07 '16 at 14:39
3

The explanation is simple. To represent the string "string\", the compiler needs "string\\" because \ is an escape character. If you use @"string\" instead, you can forget about \\.

Mage Xy
  • 1,803
  • 30
  • 36
not my real name
  • 393
  • 4
  • 16