Understand the @ symbol in C#

[@ symbol]

The @ symbol can be pretty confusing for some C# developers. I’ve even known a few who have been programming for quite a while but who still have incorrect assumptions about what @ does.

In your code (and only in your code!) a string literal may contain special two-character pairs starting with a backslash \ called “escape sequences” to represent special non-visible characters. For example, \n represents the newline character and \t represents a tab character.

If you want to place a backslash in a string, you need to “escape it” by placing another backslash in front of it so you get \\. For example, the following code puts the string “C:\temp\whatever” in the string variable my_path.

string my_path = "C:\\temp\\whatever";

If you need to type a lot of strings that contain backslashes, this gets pretty annoying. To make things a little easier, C# lets you add the @ symbol in front of a string to create a “verbatim string literal” where backslashes are not interpreted as escape characters. When you do this, you cannot embed special characters such as newlines and tabs within the string. The following code is equivalent to the previous code except it uses a string literal.

string my_path = @"C:\temp\whatever";

Remember that all of this only applies to your code and not to anything that the user enters, for example, in a TextBox or ComboBox. Anything the user types becomes part of the control’s Text property with no escaping and no special meaning attached to the \ character. You do not need to worry about treating escape characters differently in anything the user types because the user cannot enter special characters that way. In other words, the user cannot enter a tab character by typing \t.

To make matters more confusing, C# also allows you to declare a variable with a name that starts with @ to create a “verbatim identifier.” This lets you create variables named after keywords such as for and struct. Of course the variables are actually named @for and @struct so you don’t quite get to name them after the keywords.

This seems like a really bad idea in any case. It will make your code harder to read and understand. Besides, if you really need to name a variable exit, you could use an underscore in front of it to get _exit. Still confusing but at least it doesn’t drag the @ character into things to make them even more confusing.

The reason I’m worrying this issue so much is that I recently saw code similar to the following:

string user_first_name = @txtFirstName.Text;

I’m actually not completely sure what C# thinks it is doing with that @ symbol, but it does let the program continue running. What the programmer thought this did was protect the program from escape symbols, for example if the user entered \t. What it actually does is nothing. (I think it’s completely bizarre that C# even allows this.)

The following code shows how the program demonstrates various string literals and other string issues when it starts.

private void Form1_Load(object sender, EventArgs e)
    txtDoubleSlash.Text = "C:\\temp\\whatever";
    txtAtSign.Text = @"C:\temp\whatever";
    txtFirstLabel.Text = label1.Text;
    txtSecondLabel.Text = label2.Text;

    // Some poorly named variables that use @.
    string[] @foreach = { "A", "B", "C" };
    foreach (string _foreach in @foreach)

    // Adding an @ doesn't change a TextBox's contents.

The code first displays two strings containing embedded backslashes in text boxes. The first statement escapes the backslashes. The second uses a verbatim string literal.

Next the code copies the text from two Label controls into two TextBox controls in the form’s upper left. Notice that the result in the picture shows the values as they appear in the Label controls with no escaped craziness. The values in the Label controls’ Text properties are as they should be and escaping doesn’t apply.

The code then demonstrates a really confusing loop that uses the @ and _ symbols to make variables look like keywords. A bad idea!

The code finishes by displaying the text in the top TextBox with and without the @ symbol added to the statement. The results are the same regardless of whether there are backslashes in the TextBox.

If you enter some text in the TextBox above the button and then click the button, the following code executes.

private void btnShowValue_Click(object sender, EventArgs e)
    txtResult.Text = txtEnteredValue.Text;

This code displays the value entered in the TextBox. Again notice that it doesn’t need to do anything about escape sequences.

In summary, you only need to worry about escape sequences or the @ symbol in string literals within your code. You don’t need to worry about them in text typed by the user. This program doesn’t demonstrate it, but you also don’t need to worry about them in text that you read from a file or other data source.

And don’t make verbatim identifiers. They’re just plain confusing!

(Sorry to beat this issue to death but I do see a lot of confusion and mythology surrounding this issue.)

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in strings, syntax and tagged , , , , , , , , , , . Bookmark the permalink.

6 Responses to Understand the @ symbol in C#

  1. Anonymous says:

    The @ symbol for non-string-literals is for letting you use keywords as variable names (like square bracketed variables in VB):

    string @string = “blah”;

    Obviously not a good idea, but sometimes unavoidable if you’re working multiple languages and run into a named param that is a keyword in C# but not a keyword in the original defining language.

  2. Help says:

    I have a question. I am making a syntax highlighter, what I need is for it to recognize @”path” as a string. I don’t know how to write “@” sign into a string.

    private bool isString(char c)
            if (c.Equals('\@"')) // this doesn't work
                return true;
  3. Joe Eggers says:

    One valid use case for the @ in front of variable names is when generating C# code from user-entered input. If you are creating some kind of editor, say, and you’re going to create classes or variables to implement in code what the user enters as strings, you don’t really want to have to do a language-aware scan of their input before you generate a class with their provided name. And they might well use words like Class, public, etc. depending on the domain they are working in. With @ you can take their input verbatim. For example, the Unity development environment does exactly this.

  4. Sinan Basalan says:

    I miss your articles that I really follow up on Twitter. But you have been not around since March. I would love to look forward to see your articles.

Comments are closed.