Home » c# » C# '@' before a String [duplicate]

C# '@' before a String [duplicate]

Posted by: admin November 30, 2017 Leave a comment

Questions:

Possible Duplicate:
What's the @ in front of a string for .NET?

I found this in a C# study book

DirectoryInfo dir = new DirectoryInfo(key.Key.ToString() + @":\");

The book however did not explain what the ‘@’ symbol was for. I tried searching MSDN C# Operators but its not listed there. I can guess that it allows the developer to not have to escape a ‘\’ or does it allow to not have any escape sequences?

What is this for and why would I use @":\" instead of ":\\"?

Thanks for the help

Edit: See the comment below for a similar question

Answers:

It means to interpret the string literally (that is, you cannot escape any characters within the string if you use the @ prefix). It enhances readability in cases where it can be used.

For example, if you were working with a UNC path, this:

@"\servername\share\folder"

is nicer than this:

"\\servername\share\folder"

Questions:
Answers:

It also means you can use reserved words as variable names

say you want a class named class, since class is a reserved word, you can instead call your class class:

IList<Student> @class = new List<Student>();

Questions:
Answers:

Prefixing the string with an @ indicates that it should be treated as a literal, i.e. no escaping.

For example if your string contains a path you would typically do this:

string path = "c:\mypath\to\myfile.txt";

The @ allows you to do this:

string path = @"c:\mypath\to\myfile.txt";

Notice the lack of double slashes (escaping)

Questions:
Answers:

As a side note, you also should keep in mind that “escaping” means “using the back-slash as an indicator for special characters”. You can put an end of line in a string doing that, for instance:

String foo = "Hello\

There";

Questions:
Answers:

What is this for and why would I use @”:\” instead of “:\”?

Because when you have a long sting with many \ you don’t need to escape them all.