Difference Between a Regular String and a Verbatim String

What is the difference between a regular string and a verbatim string?

A verbatim string is one that does not need to be escaped, like a filename:

string myFileName = "C:\\myfolder\\myfile.txt";

would be

string myFileName = @"C:\myfolder\myfile.txt";

The @ symbol means to read that string literally, and don't interpret control characters otherwise.

What is a verbatim string?

It means that special chars don't need to be escaped, since you informed the compiler to expect special characters, and to ignore them. A common use case might be to specify a connection string:

string sqlServer = @"SERVER01\SQL"; 

This is perfectly valid, as opposed to in normal use where the backslash would be considered an escape character.

Verbatim string literals v escape sequences

Any difference here is limited strictly to the compiler; the IL and runtime have no concept of verbatim vs escaped - it just has the string.

As for which to choose: whichever is more convenient ;p I almost always use verbatim string literals if there are unusual characters, as that allows for multi-line strings very easily and visually.

As an interesting case:

bool areSame = ReferenceEquals("c:\\somewhere", @"c:\somewhere"); // true

which tells are they are exactly the same string instance (thanks to "interning"). They aren't just equivalent; they are the same string instance to the runtime. It is therefore impossible that they can be (to the runtime) different in any way.

How do I escape in verbatim string?

Use a double quote:

 string s2 = @"This is \t a ""verbatim"" string";

With C# 11 you could also use a raw string literal, for example:

string longMessage = """
This is a long message.
It has several lines.
Some are indented
more than others.
Some should start at the first column.
Some have "quoted text" in them.
""";

Raw string literals are a new format for string literals. Raw string literals can contain arbitrary text, including whitespace, new lines, embedded quotes, and other special characters without requiring escape sequences. A raw string literal starts with at least three double-quote (""") characters. It ends with the same number of double-quote characters.

How to have a verbatim string literal inside a verbatim string literal?


string mystring = "CMD.AddParameters(\"@Pkey\", SqlDbType.Int, Pkey.ToString());";

or

string mystring = @"CMD.AddParameters(""@Pkey"", SqlDbType.Int, Pkey.ToString());";

Verbatim string replace

You declared string a to end with carriagereturn character:

var a = "asdfgh\r"; //it has a length of 7 when compiled 

So you must replace the carriage return with nothing:

Replace("\r","")

If you had declared the string to end with "backslash r":

var a = @"asdfgh\r"; //it has a length of 8 when compiled 

Then you would have succeeded in replacing "backslash r" with nothing:

Replace(@"\r","")

This would also work:

Replace("\\r","")

Because the double slash is turned into a single and then the r is a normal character so you're replacing "backslash r" and not carriagereturn


When compiling the C# compiler looks for \ in a string and converts the following character(s) according to some rule. Using @ before the string turns this off. Mostly it's useful for paths. Remember that it's a compile time thing, not something you need to do to variables that hold data entered in runtime. Putting an @ before a variable name means something different - allowing you to call a variable a reserved word, like string @for = "for" - deplorable practice; don't do it

Ultimately the problem is that you were inconsistent when declaring your strings - a was not a verbatim string so it really did have a single carriage return char, and then you were trying to replace using a verbatim string (and "backslash r" is a different string to "carriagereturn"

What are all the usages of '@' in C#?


Strings literals

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.

Example 1:

@"C:\Path\File.zip" == "C:\\Path\\File.zip"

// where

"C:\\Path\\File.zip" // regular string literal
@"C:\Path\File.zip" // verbatim string literal

Note: In verbatim string literals you should escape double quotes.

Example 2:

@"He said: ""Hello""" == "He said: \"Hello\""

More info here:

  • string (C# Reference) at MSDN
  • String literals at MSDN
  • String Basics (C# Programming Guide) at MSDN
  • Working with Strings in C#
  • Strings in .NET and C#

Identifiers

The prefix "@" enables the use of keywords as identifiers, which is useful when interfacing with other programming languages. The character @ is not actually part of the identifier, so the identifier might be seen in other languages as a normal identifier, without the prefix. An identifier with an @ prefix is called a verbatim identifier. Use of the @ prefix for identifiers that are not keywords is permitted, but strongly discouraged as a matter of style.

Example:

class @class
{
public static void @static(bool @bool) {
if (@bool)
System.Console.WriteLine("true");
else
System.Console.WriteLine("false");
}
}
class Class1
{
static void M() {
cl\u0061ss.st\u0061tic(true);
}
}


Related Topics



Leave a reply



Submit