I use @ symbol with local path only, but when do I use @ exactly?
AFAIK, You can use @ at any place where you don't want to let the default meaning of the thing persist. For example, @class will make class an identifier. @bool will make bool an identifier instead of a keyword.
You know the usage of @ before strings. It is used to indicate that take all the text of the string literally and don't treat any character in the string specially.
Edit: An yes, another thing to this is that @Keyword
is compiled into a Keyword
in IL.
See this Link for more details.
An @
before a string literal in C# denotes a verbatim string. In a verbatim string, only the quote escape sequence (""
) is parsed as an escape sequence; all others, e.g. \n
, \t
etc. are ignored.
You'll have seen this syntax used with file paths, etc. because it's convenient to have the compiler ignore the backslashes in the path, rather than having to double-escape them, e.g.
var s = @"c:\Some\File\Path.txt";
is a little easier to read than
var s = "c:\\Some\\File\\Path.txt";
You can also prefix identifiers with @
in order to allow using reserved words in identifiers. For example, @class
can be used as an identifier, whereas class
wouldn't be permitted. In this specific case, @class
is a little less jarring (at least, I find) than the usual convention of klass
or clazz
which are often used to work around this restriction in other languages.
You can prefix a string with the @ sign to avoid having to type 2 backslashes to mean one backslash. This is why it is often used for local path because it saves some typing, and simplifies what you are looking at when you read it later. When you have a bunch of double quotes and other escape characters, aka special characters - that's when you want the @ sign. When you use the @ sign, make sure to put just one backslash when you mean backslash. When using the @ you want to use the double quote character, put two double quotes instead of backslash, double quote.
String path = "C:\\path\\to\\my\\file";
vs
String path = @"C:\path\to\my\file"; //@ says one backslash is enough
here is another example:
String quotation = "He said, \"Wow!\""; //backslashes say not to end string
vs.
String quotation = @"He said, ""Wow!"""; //need a different method of denoting double quote
If you want to use keywords as variable names
string @string = "Hi";
You use @ before strings to avoid having to escape special characters.
This from the MSDN:
The advantage of @-quoting is that escape sequences are not processed, which makes it easy to write, for example, a fully qualified file name:
@"c:\Docs\Source\a.txt" // rather than "c:\\Docs\\Source\\a.txt"