Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

c#

.net

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.

like image 267
Klaw Avatar asked Feb 17 '09 09:02

Klaw


People also ask

What is L before string in C++?

L is the prefix for wide character literals and wide-character string literals which tells the compiler that the char or string is of type wide-char. w is prefixed in operations like scanning (wcin) or printing (wcout) while operating wide-char type.

How do you find the beginning of a string?

The startsWith() method of String class is used for checking prefix of a String. It returns a boolean value true or false based on whether the given string begins with the specified letter or word.

What does do before a string in C#?

It means to interpret the string literally (that is, you cannot escape any characters within the string if you use the @ prefix). It enhances readability in cases where it can be used.

What is verbatim string literal?

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


Video Answer


2 Answers

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

like image 191
Richard Ev Avatar answered Oct 14 '22 09:10

Richard Ev


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."; 
like image 27
Jon Skeet Avatar answered Oct 14 '22 08:10

Jon Skeet