Click here to Skip to main content
15,888,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Tonight while laying out a program to open and parse a file I came across something I've never seen before. In the text I'm using for learning examples, all of the file specs in statements begin with @ followed by the actual file path. The book doesn't explain it, and the character is missing from the index. I checked examples from Microsoft, and the mysterious @ symbol is there, as well, also without explanation.

I've programmed in a lot of languages, but I've never seen this before. What's it for? What's wrong with using just a string?

All the examples I've looked at tonight use a hard-coded filename (e.g. "C:\Target\MyFile.txt"), but I'm using a string variable acquired by using an OpenFileDialog. Do I still need to prepend the '@' symbol to my variable in order to reference the file properly? Does this apply to all .Net languages, or just C#?

Ordinarily I'd just spend the hours required to write the code several different ways until it works, but it's late and I'm short of sleep, and I'd really like to make some serious progress tomorrow night after work. I'd appreciate an explanation of the use of this character, and why/when it's required. That would save me many hours I don't have available. :)
Posted

1 solution

The advantage of @-quoting is that escape sequences are not processed, which makes it easy to write.

As an example, I cannot use \ in my string as it is an escape sequence.
So I need to use a \\ which essentially means a single "\" in C# (when compiled).

Instead I could use the @ operation.

string strPath = @"C:\Docs\Source\a.txt"; rather than strPath = "c:\\Docs\\Source\\a.txt";.
 
Share this answer
 
v2
Comments
Roger Wright 24-Sep-10 2:35am    
So the @ character causes the compiler to treat as literals the characters that would normally be processed as special escaped characters? Sweet! Why didn't they do that long ago?

Thanks, Abhinav! :-D

Does that mean I have to add the @ character in front of my variable, or can I just use the variable as is?
Abhinav S 24-Sep-10 2:49am    
This is not really required for variables but rather for constants in code. Besides, you need not use the @ character against all constants (by constants here I mean the literal for e.g. the hard coded file path). It is only where you are going to use an escape character sequence that you need to use @.
Toli Cuturicu 24-Sep-10 7:02am    
"Why didn't they do that long ago?": They did it a very long time ago. Actually, from the beginning, c# supported verbatim strings (as these are called).

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900