[ACCEPTED]-Using the literal '@' with a string variable-string

Accepted answer
Score: 14

I don't think you have to worry about it 5 if you already have the value. The @ operator 4 is for when you're specifying the string 3 (like in your first code snippet).

What are 2 you attempting to do with the path string 1 that isn't working?

Score: 4

I'm not sure if I understand. In your example: if 7 helper.getFilePath() returns "c:\somepath\file.txt", there will be no problem, since 6 the @ is only needed if you are explicitely 5 specifying a string with "".

When Functions 4 talk to each other, you will always get the literal path. If 3 the XML contains c:\somepath\file.txt and your function returns 2 c:\somepath\file.txt, then string filePath will also contain 1 c:\somepath\file.txt as a valid path.

Score: 3

The @"" just makes it easier to 11 write string literals.

string (C# Reference, MSDN)

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

@"good morning" // a string literal

The advantage 8 of verbatim strings is that escape sequences 7 are not processed, which makes it easy to 6 write, for example, a fully qualified file 5 name:

@"c:\Docs\Source\a.txt" // rather than "c:\\Docs\\Source\\a.txt"

One place where I've used it is in 4 a regex pattern:

string pattern = @"\b[DdFf][0-9]+\b";

If you have a string in 3 a variable, you do not need to make a "literal" out 2 of it, since if it is well formed, it already 1 has the correct contents.

Score: 2

In C# the @ symbol combined with doubles 5 quotes allows you to write escaped strings. E.g.

print(@"c:\mydir\dont\have\to\escape\backslashes\etc");

If 4 you dont use it then you need to use the 3 escape character in your strings.

http://msdn.microsoft.com/en-us/library/aa691090(VS.71).aspx

You dont 2 need to specify it anywhere else in code. In 1 fact doing so should cause a compiler error.

Score: 1

You've got it backwards. The @-operator 5 is for turning literals into strings, while 4 keeping all funky characters. Your path 3 is already a string - you don't need to 2 do anything at all to it. Just lose the 1 @.

string filePath = helper.getFilePath();
Score: 1

The string returned from your helper class 3 is not a literal string so you don't need 2 to use the '@' character to remove the behaviour 1 of the backslashes.

More Related questions