I have the following string @"\servidor01\arquivos"
. What is the function of @
in front of string ?
I have the following string @"\servidor01\arquivos"
. What is the function of @
in front of string ?
It means a string literal, or a string raw, without considering escape characters.
The \
character acts as escape to insert special characters in string , and because it is a network address, you really want this character to be considered.
If you do not use @
, you would have to duplicate the backslash in this way:
string a = "\\servidor01\arquivos"
Here are some other examples of the content that the variable will display.
string a = "hello, world"; // hello, world
string b = @"hello, world"; // hello, world
string c = "hello \t world"; // hello world
string d = @"hello \t world"; // hello \t world
string e = "Joe said \"Hello\" to me"; // Joe said "Hello" to me
string f = @"Joe said ""Hello"" to me"; // Joe said "Hello" to me
string g = "\\server\share\file.txt"; // \server\share\file.txt
string h = @"\server\share\file.txt"; // \server\share\file.txt
string i = "one\r\ntwo\r\nthree";
string j = @"one
two
three";
Reference: Microsoft Docs
I have two add-ons on the subject.
The @
can be used for something else in the language. When you need to use an identifier that conflicts with a reserved word, this symbol can be used to indicate that it is an identifier and to resolve the ambiguity. Example:
var @lock = true;
This may be necessary for legacy codes and especially when you use a library written in another language where that word is not reserved.
In C # 6 there is a new symbol to indicate a special condition of that string . With the addition of string interpolation, we can use the variable (and maybe an expression) within string . For this the compiler needs to understand that this is being used on it. It would look like this:
var texto = $"Contei {x} vezes";
The $
indicates that what the {}
snippet needs to be resolved at runtime. Read more about it .
To better understand the representation of strings in C #, I suggest reading the articles:
String (C # Reference) and String literals
Briefly, C # supports two types of string representation:
textual string (verbatim) that consists of a quoted string preceded by the @ character. Text strings do not process escaped combinations.
Examples:
string a = "Hello"; // string regular
string b = @"Hello"; // string textual
string c = "Hello \n World"; // string regular com o escape \n de quebra de linha
string d = @"Hello \n World"; // string textual não processa combinação escape
// strings textuais podem expandir por múltiplas linhas
string e = @"SELECT *
FROM Funcionario
WHERE nome LIKE '%Silva%'";
It is a reserved language word, to escape string.
string arquivo = @"c:\arquivo.txt";