Click here to Skip to main content
15,895,142 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
Hello,

I've been experimenting with C# for some time now, and I keep seeing the @ character and can not find what it does exactly.
I saw it beeing used in file paths, and today I saw it somewhere else and could not figure the purpose.

Can someone explain what the exact meaning/purpose/use of the @ character is?

Code snippets where I saw it used:
C#
string SoftwareKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";

C#
if (printerName.Equals(@"hp deskjet 930c"))

C#
private string sbfFilePath = Application.StartupPath + @"\lukas.sbf";
Posted

In all above cases @ is used to allow escape character.
If you write this
C#
string SoftwareKey = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";

It will give you syntax error.
So you can use this
C#
string SoftwareKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
This is difficult way so instead
C#
string SoftwareKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";



Now overall use of @
You can use reserverd keyword
1.
C#
string for;
is not allowed but below code is allowed
C#
string @for;


2.To allow escape character as above example.

3.To use multiline text
C#
Label1.Text="First line \n Second Line ";

Insted of this use this
C#
Label1.Text= @"First line
                 Second Line ";

So here @ sign take line how it is written.
 
Share this answer
 
The '@' character before a string turns off character escaping. Without it, any character following a '\' character is interpreted as a special code:
\n   Newline
\t   Tab
\\   A single '\' character
\"   A single '"' character

and so on.

So
C#
string s = "\\\"\\\"";
would give you a string containing:
A backslash
A doublequote
A backslash
A doublequote


Prefixing it with '@' turns that off:
C#
string s = @"\""\";
Will give you the same result, which makes paths, regexes and so forth a lot more readable:
@"D:\Temp\MyFile.txt"
As opposed to
"D:\\Temp\\MyFile.text"


If you turn off escaping, to enter a double quote, you enter two of them together:
C#
string s = "hello ""Paul"" - this is a string"
 
Share this answer
 

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