What's the @ in front of a string in C#?

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


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.";

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.

Tags:

C#

.Net

String