Reputation: 12497
There is a type of string in which you disable the processing of a literal’s escape characters and print the string as is. What is this string? What is the symbol used to prefix the string, and a possible use for?
Is it \
?
Upvotes: 7
Views: 3029
Reputation: 5298
If I had a string such as c:\monkey.txt
, I would have to escape the slash like this:
`string s = "c:\\monkey.txt" `
Notice the double slash.
Alternatively, you can use the '@' symbol to indicate that the string is to be taken literally:
`string s = @"c:\monkey.txt"`
Upvotes: 2
Reputation: 1499800
It's called a verbatim string literal, and uses the @ prefix.
Without the prefix, it's still a string literal - it's a regular string literal.
(Some people mistakenly think that the term "string literal" only applies to verbatim string literals, but it's more general than that.)
Verbatim string literals are useful for:
Note that this only makes a difference at compile time. In other words, these two statements are precisely equivalent:
string x = "foo\\bar"; // Regular string literal
string x = @"foo\bar"; // Verbatim string literal
Verbatim string literals are still interned in the same way as regular string literals, still refer to instances of System.String
etc.
From section 2.4.4.5 of the C# 4.0 specification:
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.
Note that @ can also be used as a prefix to allow you to use keywords as identifiers:
int class = 10; // Invalid
int @class = 10; // Valid
This is rarely useful, but can sometimes be required if you have to use a particular identifier. (The class
keyword can be useful for an anonymous type property in ASP.NET MVC, for example.)
Upvotes: 8
Reputation: 52518
In C# you can use the @ sign to make a verbatim string literal.
All but the \" are ignored.
var literal = @"C:\Test\Test.txt
Newlines are also parsed";
Upvotes: 2
Reputation: 562
@
string sLiteral = @"This will be formatted. Even including
return characters,
and spaces at the start of lines";
Upvotes: 5
Reputation: 41232
It is the @
character: @"c:\path"
It is called a verbatim string literal.
Upvotes: 15