C# Tips & Tricks #26 – 3 uses of the @ Symbol

This blog post will explain 3 different use cases of the @ Symbol in C# and how the .NET developers can use them.

3 uses of the @ Symbol in C#

1. You can use one of the reserved words of c# with the this symbol

Eg :

string @int = "senthil kumar";

or something like this

string @class ="MCA";

Although you can use this , avoid using one.

2. Before a string specially when using the file paths .

You can use

string filepath = @"D:\SENTHIL-DATA\myprofile.txt";

instead of

string filepath = "D:\\SENTHIL-DATA\\myprofile.txt";

3. For a Multi lined text

string ThreeIdiots = @"Senthil Kumar,
Norton Stanley,
and Pavan Rao!";

MessageBox.Show(ThreeIdiots);

instead of

string ThreeIdiots = @"Senthil Kumar,\n   Norton Stanley,and Pavan Rao!";

You can run the above code snippets using the below Run Code Snippet button.

This is what the c# Language specification states about the @ Symbol

“The prefix “@” enables the use of keywords as identifiers, which is useful when interfacing with other programming languages. The character @ is not actually part of the identifier, so the identifier might be seen in other languages as a normal identifier, without the prefix. An identifier with an @ prefix is called a verbatim identifier. Use of the @ prefix for identifiers that are not keywords is permitted, but strongly discouraged as a matter of style.”

Interesting symbol isn’t it ??

    7 Comments

  1. Joe Enos
    January 25, 2011
    Reply

    #2 and #3 are the same thing – using the verbatim string syntax allows assigning strings that are exactly as written, including backslashes and line breaks.

    Also, assuming you’re on Windows (not Mono), the line break in your example is likely rn, not just n.

  2. Chad Moran
    January 26, 2011
    Reply

    That’s more like 2 since 2 and 3 are the same thing (verbatim string literal). Though they are very nifty to know!

  3. January 26, 2011
    Reply

    yes chad , you are right to an extent ..

  4. Robert
    January 26, 2011
    Reply

    The @ symbol is now also used in the Razor View engine for ASP.NET

  5. January 26, 2011
    Reply

    @Robert . Thanks for the info . Can u let me know whet exactly it does in the Razor View Engine ?

  6. Bill Door
    January 26, 2011
    Reply

    the @ character denotes the start of a code block in .cshtml files.

  7. January 26, 2011
    Reply

    Hey Bill .. Thats interesting piece of info . Thanks

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...