Reputation: 686
I have come across some code during a code-review where a old coworker has done the following:
const string replacement = @"";
This string is used in a regex expression as a replacement for what is matched. My question is what is the purpose of adding the @ literal sign to the beginning of an empty string. There should not be anything to literally interpret.
Would there be any difference in impact between: @"";
and "";
?
Upvotes: 10
Views: 1881
Reputation: 113232
This string is used in a regex expression
Regular expressions make heavy use of the \
character. For example, the following is a regular expression to match precentages from 0
to 100
that always have four decimal places:
^(100\.0000|[1-9]?\d\.\d{4})$
Because \
has to be escaped in the more common C# syntax to \\
the @""
form allows for the regex to be more easily read, compare:
"^(100\\.0000|[1-9]?\\d\\.\\d{4})$"
@"^(100\.0000|[1-9]?\d\.\d{4})$"
And for this reason people often get into the habit of using the @""
form when they are using regular expressions, even in cases where it makes no difference. For one thing, if they later change to something where it does make a difference the only need to change the expression, not the code for the string itself.
I would suggest that this is likely why your colleague used @""
rather than ""
in this particular case. The .NET produced is the same, but they are used to using @""
with regular expressions.
Upvotes: 10
Reputation: 126042
The following:
string a = @"";
string b = "";
Generates this IL:
IL_0001: ldstr ""
IL_0006: stloc.0 // a
IL_0007: ldstr ""
IL_000C: stloc.1 // b
So no, there is no difference.
Upvotes: 5
Reputation: 27085
Look at the MSDN documention for string literals. For an empty string, it has no effect, however it changes the behavior of certain character escape sequences as well as newline handling. Examples taken from the MSDN site:
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";
Upvotes: 6