When is it better to use @ before the line?

In code declaring or using string , I usually see developers declare it like this:

 string randomString = @"C:\Random\RandomFolder\ThisFile.xml"; 

Instead:

 string randomString = "C:\\Random\\RandomFolder\\ThisFile.xml"; 

This is the only thing I see, it is better to use the @ prefix, since you do not need to do \\ , but is there any other use for it when it is better than just without it?

+4
source share
5 answers

The @ icon tells the compiler that the string is a literal string literal , and thus does not require any characters from you. Of course, not just the backslash. No escape sequences are processed by the compiler.

Whether this is β€œbetter” or not is a very difficult question to answer. This is a purely stylistic choice. Some may argue that the contents of a string are more readable when you use a string literal, instead of avoiding all characters. Others may prefer consistency when all strings containing characters that usually require escaping should be escaped. This makes it easy to spot errors in the code. (For what it costs, I fall into the last camp. All my paths have \\ .)

This, as they say, is extremely convenient for regular expressions, for which you could otherwise run everywhere. And since they are not very similar to regular strings, there is minimal risk of confusion.

+8
source

Windows path names are not the only things with a lot of backslashes. For example, @ -strings are very useful for regular expressions because they avoid double exiting from all.

They can also span multiple lines, so if you ever have to have multi-line lines in your code, they make it a little more convenient.

+5
source

simplifies regex

 @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$"; 

Row of several lines

 string s = @"testing some string with multiple lines"; 
+1
source

This is especially useful for regular expressions that are explicitly associated with a backslash character match. Since it is a special character in both C # string syntax and regex syntax, it requires "double escaping." Example:

 string regex = "\\\\.*\\.jpg" 

The same expression using @ -notation will be more accurate:

 string regex = @"\\.*\.jpg" 
+1
source

"and @" "are string literals, at first it is a regular literal, and the last is the string literal '@' prefix before any string in C # .NET (regular string literal and Verbatim string literal in C # .NET)

0
source

All Articles