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

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.

Related

On C# escape curly braces and a backslash after

I am trying to format a text so I can provide a template some RFT text.
My string is declared with the stringformater as:
var fullTitleString = string.Format(
CultureInfo.CurrentCulture,
"{{\\Test",
title,
filterName);
But I keep obtaining a string as "{\Test". Using a single backslash results on errors at it does not understand the \T escaped character.
Doing #"{{\Test" also yields "{\Test". I have looked over the MSDN documentation and other questions where they tell to use another backslash as escaping character, but it doesn't seem to work.
There are two levevls of escaping here:
1. Escaping string literals
In c# strings, a backslash (\) is used as special character and needs to be escaped by another \. So if your resulting string should look like \\uncpath\folder your string literal should be var s = "\\\\uncpath\\folder".
2. Escape format strings
string.Format uses curly braces for place holders, so you need to escape them with extra braces.
So let's say you have
string title = "myTitle";
string filterName = "filter";
then
string.Format("{{\\Test {0}, {1}}}", title, filterName);
results in
{\Test myTitle, filter}
If you want two curly braces at the beginning, you need to put four in your format string:
string.Format("{{{{\\Test {0}, {1}}}", title, filterName);
results in
{{\Test myTitle, filter}
If you provide a clear example of what you are trying to achieve, I may tell you the correct format string.
Side note: In C# 6 the last example could also be $"{{{{\\Test {title}, {filterName}}}" (using string interpolation without explicitly calling string.Format)
NOTE: The Visual Studio debugger always shows the unescaped string literal. So if you declare a string like string s = "\\" you will see both backslashes in your debugger windows, but if you Console.WriteLine(s) only one backslash will be written to console.

C# Settings with verbatim string literal

Perhaps I didn't see or understand any of the answers I read but I am having trouble using verbatim string literal (#) with settings.Default.(mysetting). I am trying to do something like
Directory.GetFiles(#Setting.Default.(mysetting),"*.txt");
and cant seem to find the right syntax to make this work.
The # identifies a string constant literal where back slashes should not be interpreted as escape signs. You can not use it in front of method invocations as you attempt here.
A valid assignment might be
string path = #"c:\temp\example.txt";
Usually a \t would be interpreted as a tabulation character thus making the file reference illegal. It is exactly identical to
string path = "c:\\temp\\example.txt" ;
But bit easier to read.
# verbatim string is used with string literals. So your code should be:
Directory.GetFiles(Setting.Default.(mysetting),#"*.txt");
because "*.txt" is the string literal in your code.
(Although not related, but you can use # with variable names see C# Variable Naming and the # Symbol)
To use # as part of a verbatim string literal, the string literal must be right there - not just a property, method, etc. that returns a string.
string myStr = #"I'm verbatim, I contain a literal \n";
string myStr2 = "I'm not\nI have a newline";
string myStr3 = #myStr2; // still contains a newline, not a literal "\n"
Using # in front of an identifier allows you to use reserved keywords as identifiers. For example:
string #if = "hello!"; // valid
It also works on non-reserved words, where it has no real effect.
string #myVar = "hello!"; // valid
string newVar = myVar; // can be referred to either way
Unless I'm missing it, you still need to wrap the string within quotation marks.

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.

C# won't escape "\"? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to use “\” in a string without making it an escape sequence - C#?
Why is it giving me an error in C# when I use a string like: "\themes\default\layout.png"? At the "d" and "l" location? It says unrecognized escape sequence. And how do I stop it from giving me an error when I use: "\"?
Thans
You need to escape it with an additional \:
string value = "\\themes\\default\\layout.png";
or use the # symbol:
string value = #"\themes\default\layout.png";
which will avoid you from doubling all \.
Or if you are dealing with paths (which is what it seems you are) you could use the Path.Combine method:
string value = Path.Combine(#"\", "themes", "default", "layout.jpg");
You're using a backslash to escape 't' and 'd'. If you want to escape the actual backslash you need to do so:
"\\themes\\default\\layout.png"
"Regular" string literals treat the \ character as a special character, used for escape sequences to insert quickly special characters in strings - \n, for example, is used to insert the newline character, \" is used to insert the " character without terminating the string, and so on.
Because of this, to insert a backslash into a "normal" string you have to insert the corresponding escape sequence, which, unsurprisingly, is \\; you would then write in your case:
"\\themes\\default\\layout.png"
Failing to escape the backslashes will result in weird results or errors like the ones you got, since the compiler will try to interpret the couple backslash-letter that follows it as an escape sequence; if such sequence is defined you'll get unwanted characters (e.g. the first \t is escaped to a tab character), if it's not (like \l) you'll get an error about an undefined escape sequence.
Another option, if you don't need to escape any character, is to use the so-called "verbatim" strings literals: if you prefix the string with an # character the escape sequences will be disabled, and the string you write will be taken verbatim by the compiler. The only exception to this rule is for quotes, that can be inserted inside the verbatim string via the "quote escape sequence", i.e. "". In your case you would write:
#"\themes\default\layout.png"
For more info about regular vs verbatim string literals have a look at their documentation.
The backslash is treated as an escape character. Either escape the backslash itslef in the string like so:
"\\themes\\default\\layout.png"
or disable escaping altogether using a verbatim string literal:
#"\themes\default\layout.png"

#(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).

Categories