Difference between $ and # c# [duplicate] - c#

This question already has answers here:
Closed 12 years ago.
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

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"

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>();

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)

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";

What is this for and why would I use #":\" instead of ":\"?
Because when you have a long string with many \ you don't need to escape them all and the \n, \r and \f won't work too.

Related

How do I write a backslash (\) in a string?

I want to write something like this C:\Users\UserName\Documents\Tasks in a textbox:
txtPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)+"\Tasks";
I get the error:
Unrecognized escape sequence.
How do I write a backslash in a string?
The backslash ("\") character is a special escape character used to indicate other special characters such as new lines (\n), tabs (\t), or quotation marks (\").
If you want to include a backslash character itself, you need two backslashes or use the # verbatim string:
var s = "\\Tasks";
// or
var s = #"\Tasks";
Read the MSDN documentation/C# Specification which discusses the characters that are escaped using the backslash character and the use of the verbatim string literal.
Generally speaking, most C# .NET developers tend to favour using the # verbatim strings when building file/folder paths since it saves them from having to write double backslashes all the time and they can directly copy/paste the path, so I would suggest that you get in the habit of doing the same.
That all said, in this case, I would actually recommend you use the Path.Combine utility method as in #lordkain's answer as then you don't need to worry about whether backslashes are already included in the paths and accidentally doubling-up the slashes or omitting them altogether when combining parts of paths.
To escape the backslash, simply use 2 of them, like this:
\\
If you need to escape other things, this may be helpful..
There is a special function made for this Path.Combine()
var folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var fullpath = path.Combine(folder,"Tasks");
Just escape the "\" by using + "\\Tasks" or use a verbatim string like #"\Tasks"
txtPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)+"\\\Tasks";
Put a double backslash instead of a single backslash...
even though this post is quite old I tried something that worked for my case .
I wanted to create a string variable with the value below:
21541_12_1_13\":null
so my approach was like that:
build the string using verbatim
string substring = #"21541_12_1_13\"":null";
and then remove the unwanted backslashes using Remove function
string newsubstring = substring.Remove(13, 1);
Hope that helps.
Cheers

Why assign a string with #? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What's the # in front of a string in C#?
This is something I have questioned for a long time but never bothered to figure out. When I download third party libraries I have often seen string assignments using a # symbol before the string.
string myString = #"Some text";
But there seems to be absolutely no difference if I simply do
string myString = "Some text";
So what is the # doing?
It is signifies a verbatim string literal and allows you to not have to escape certain characters:
string foo = #"c:\some\path\filename.exe";
vs:
string foo = "c:\\some\\path\\filename.exe";
string reason = #"this string literal mea\ns something different with an # in front than without";
Without the #, the above string would have a new-line character instead of an 'n' in the word "means". With the #, the word "means" looks just like you see it. This feature is especially useful for things like file paths:
string path = #"C:\Users\LookMa\NoDoubleSlashes.txt";
It is a verbatim string literal. It lets you do things like #"C:\" instead of "C:\\", and is especially useful in regex and file paths, since these often use backslashes that shouldn't be parsed by the compiler. See the documentation for more info.
In this case there is no difference.
All '#' does is allow you to omit escape backslashes. If you use '#' and want in include double quotes in the string you need to double up the double quotes.

#(at) sign in file path/string [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What's the # in front of a string for .NET?
I have the following code:
new Attachment(Request.PhysicalApplicationPath + #"pdf\" + pdfItem.Value)
What does the # sign do?
It has nothing to do with filepath. It changes the escaping behavior of strings.
In a string literal prefixed with # the escape sequences starting with \ are disabled. This is convenient for filepaths since \ is the path separator and you don't want it to start an escape sequence.
In a normal string you would have to escape \ into \\ so your example would look like this "pdf\\". But since it's prefixed with # the only character that needs escaping is " (which is escaped as "") and the \ can simply appear.
This feature is convenient for strings literals containing \ such as filepaths or regexes.
For your simple example the gain isn't that big, but image you have a full path "C:\\ABC\\CDE\\DEF" then #"C:\ABC\CDE\DEF" looks a lot nicer.
For regular expressions it's almost a must. A regex typically contains several \ escaping other characters already and often becomes almost unreadable if you need to escape them.
It's a verbatim string literal.
This allows the string to contain backslashes and even linebreaks without them being handled differently:
string multiLineString = #"First line
second line
third line";
As backslashes aren't used for escaping, inserting a double quote into the string requires it to be doubled:
string withQuote = #"before""after";
Verbatim string literals are typically used for file paths (as you've shown) and regular expressions, both of which frequently use backslashes.
See my article on strings for more information.
It allows you to enter the backslash (\) without escaping it:
var s1 = "C:\\Temp\\MyFileName";
var s2 = #"C:\Temp\MyFileName";
Both result in a string with the same contents (and since strings are interned at compile time, probably even the same string reference).

C# '#' before a String [duplicate]

This question already has answers here:
Closed 12 years ago.
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
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"
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>();
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)
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";
What is this for and why would I use #":\" instead of ":\"?
Because when you have a long string with many \ you don't need to escape them all and the \n, \r and \f won't work too.

in C#, What does the "#" symbol do? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What's the # in front of a string for .NET?
Sometimes i saw the sample code, will have a "#" symbol along with the string.
for example:
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.Provider = "System.Data.SqlServerCe.3.5";
entityBuilder.ProviderConnectionString = providerString;
entityBuilder.Metadata = #"res://*/App_Data.data.csdl|res://*/App_Data.data.ssdl|res://*/App_Data.data.msl";
On the 4th line, what is that usage of the "#"?
I try to remove this, it still works.
A string literal such as #"c:\Foo" is called a verbatim string literal. It basically means, "don't apply any interpretations to characters until the next quote character is reached". So, a verbatim string literal can contain backslashes (without them being doubled-up) and even line separators. To get a double-quote (") within a verbatim literal, you need to just double it, e.g. #"My name is ""Jon""" represents the string My name is "Jon". Verbatim string literals which contain line separators will also contain the white-space at the start of the line, so I tend not to use them in cases where the white-space matters. They're very handy for including XML or SQL in your source code though, and another typical use (which doesn't need line separators) is for specifying a file system path.
Taken from
It tells the compiler not to treat \ as escape sequences and take the strings literally.

Categories