开发者

What does "@" mean in C# [duplicate]

This question already has answers here: Closed 12 years ago.

Possib开发者_开发百科le Duplicate:

when to use @ in c# ?

F.e. string sqlSelect = @"SELECT * FROM Sales".


It means interpret the following string as literal. Meaning, the \ in the string will actually be a "\" in the output, rather than having to put "\\" to mean the literal character


Before string it allows different string formating rules. You can't use backslash to specify special symbols and "" (double quotes become quotes). I find this format very useful for regular expressions

Example

Console.WriteLine(@"\n""\/a"); // outputs \n"\/a 
Console.WriteLine("\\n\"\"\\/a"); // outputs \n"\/a

You might also seen @ symbol before variable. In such case it allows using special C# keywords as variables.

Example:

var @switch = 1;
var @if = "test";


It means there is no need to escape characters in such a string.

So if you want to write the path for c:\Windows, you can write it as

string path = "c:\\Windows";  // Note escaped '\'

OR

string path = @"c:\Windows";  // '\' need not be escaped


There are two types of string literals, regular and verbatim. The @ symbol makes it a verbatim string literal.

MSDN: String literals (C#)


In C and C++, string has some special characters called "escape characters". For example \, & and the " itself is an escape character!

In the very normal way, you to print a statement like:

Nancy Said Hello World! & smiled

you had to set your string like next

string str = "Nancy said Hello World! \& smiled.";

But people in Microsoft made a new cool feature in C# compiler so you can escape the headache of handling the escape characters by adding @ before any string, and the compiler will handle all the escape characters for you by himself. For the last example you can have this in C# like next:

string str = @"Nancy said Hello World! & smiled.";


Verbatim string literals start with @ and are also enclosed in double quotation marks. For example:

@"good morning"  // a string literal

Nicked from, have a look at the last few lines above the example for more information. http://msdn.microsoft.com/en-us/library/362314fe.aspx


Used for string literal. It marks the string within the quote (") marks as the value without applying any interpretation for symbols in that string.


It allows you to have a string with a \ delimiter in it. @"C:\A\b\c\d\e\f" is legal.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜