How do you use this # in C#? - c#

simpleSound = new SoundPlayer(#"c:\Windows\Media\chimes.wav");
Why and what is the # for?

It's a literal string. Instead of having to escape the "\" by putting two of them "\" the compiler interprets the string "as is".
Say you wanted to print out the following text to the screen: "Hello \t world".
If you were to just do Console.WriteLine("Hello \t world"), then your output would be:
Hello world
notice the tab. That's because \t is interperted as a tab. If you use the literal though, like this:
Console.WriteLine(#"Hello \t world")
then your output would be:
"Hello \t world"

The # sign before a string means to treat the backslash as a normal character rather than the start of a special character (such as newline).

It identifies a string literal. It allows you to have the special character \ in the string without escaping it.

It is a verbatim string. A verbatim string allows you to include special characters like \, " etc. without using the escape sequence.

Another usage of # is that you can put it in front of a keyword, if you want to use a keyword as a variable name (even if it's not a good idea). Example:
public int #object = 1;

Defining the # symbol prior to the assigning a string value will prevent the need for doubling the backslash (\) in C#. The at symbol (#) simply ignores escape characters.

"c:\\my\\file.txt" could be done as #"c:\my\file.txt"
This means your \n and \t or whatever it is will also not be processed.

Related

Escape character in c#

I stuck in escape sequence in program.
I am getting input from xml file in single quotes.
So in string it may contain any escape sequence.
So what I want to do is consider next character after escape character as normal character.
Example: '\abc\\t'
Output: 'abc\t'
So for that I created regular expression which is:
Regex.Replace(SearchString, #"\\?(?<Character>)", "${Character}");
But it replaces all escape character and gives output :
abct
Please help me how can I do it?
The named group in your regular expression matches nothing, so it does the same as Replace(#"\", "").
Match one character in the group:
SearchString = Regex.Replace(SearchString, #"\\(.)", "$1");
Basically, you need parse your string character by character. Pseudo-code:
Loop through all characters c:
If c is escape character:
Read next character and do something special (\t is tab, \\ is backslash, ...)
Else:
Copy character to output
Try this:
Regex.Replace(SearchString, #"\\(?<Character>[^\\])", "${Character}");
What if you do like:
SearchString = SearchString.Replace(#"\\", #"\");
It would give:
\abc\t
Here escaped \t is now treated as a "tab character".
It is what you are looking for ?

Regex, MVS does not like my Regex strings, how do I make it comply

So in microsoft visual studio I have a string that is compiled into a regex. My string is "#(\d+(.\d+)?)=(\d+(.\d+)?)". I cannot compile my program because I get an error saying that \d is a unrecognized escape character. How do I tell it to shut up and let me regex like a pro?
Begin your string with #, that causes the compiler to leave (almost) all characters alone, unescaped (the exception is ", which can be escaped as ""):
#"#(\d+(.\d+)?)=(\d+(.\d+)?"
The problem is that c# does not like the \d inside the string. Use a verbatim string instead
string pattern = #"#(\d+(.\d+)?)=(\d+(.\d+)?)";
The "#" denotes it. C# will not look for escape sequences in the string. If you have to escape a " use two "".
Of cause you can use normal strings. but then you will have to escape the backslashes
string pattern = "#(\\d+(.\\d+)?)=(\\d+(.\\d+)?)";
If you're using a normal string, you need to escape your backslashes, like so:
"#(\\d+(.\\d+)?)=(\\d+(.\\d+)?)"
Basically, you're putting a literal string into C#; the C# compiler sees the string first, and tries to interpret \d as an escape sequence (which doesn't exist, hence error). Therefore, you use \\d to get the C# compiler to see the string as \d, which then gets passed to the regex engine (which does recognize \d as something meaningful). (yes, if you want to match a literal backslash in your regex pattern, you need to use \\\\)
But in C#, you have the alternative of just prepending the string with # to get the compiler to leave the string alone (though " still needs escaping), so that would be like this:
#"#(\d+(.\d+)?)=(\d+(.\d+)?)"
You could also use a verbatim string literal (I prefer to use these because of readability).
Use #"(#\d+(.\d+)?)=(\d+(.\d+)?)"
The #" sign indicates that the string shouldn't interpret escaped characters (A character prefixed by a \) until the closing " is reached.
Note: You can match a single " in your search pattern by double quoting instead "". For instance you can match "Hello" by using the pattern #"""\w+"""

C#, escape double quote not working as expected

I'm trying to escape quotes in an xpath string like so:
var mktCapNode = htmlDoc.DocumentNode.SelectSingleNode("//*[#id=""yfs_j10_a""]");
The actual string I want passed is:
//*[#id="yfs_j10_a"]
This gives a compiler errors: ) expected and ; expected
I'm sure it's simple but I'm stumped. Any ideas?
You need to make this a verbatim string to use the "" as an escape
#"//*[#id=""yfs_j10_a""]"
For a normal string literal you need to use backslashes to escape the double quotes
"//*[#id=\"yfs_j10_a\"]"
Or use the escape char '\':
"//*[#id=\"yfs_j10_a\"]"
In C# the \ character is used to escape (see documentation).
This is different from VB where there are no escape characters except "" which escapes to ".
This means in C# you do not need vbCrLf to start a new line or vbTab to add a tab character to a string. Instead use "\r\n" and "\t".
You can also make the string a literal using the # character, but I do not think this works with the quotation mark.
Add the # prefix to your string.
#"//*[#id=""yfs_j10_a""]"
or escape the quotes with a \
"//*[#id=\"yfs_j10_a\"]"

\tssr>"&\8=f23' as String C#

I have a short question.
I want do put this \tssr>"&\8=f23' into a String (Language C#).
But the compiler always shows an error because for example "\8" is a command.
can someone help me?
Thank you very mutch.
string s = "\\tssr>\"&\\8=f23'";
OR
string s = #"\tssr>""&\8=f23'";
try
string s = #"\tssr>\"&\8=f23";
For double quote[EDIT]
string s = #"\tssr>""&\8=f23";
because \ is special char you need to escape it with either # for \\ as given in below answer
Just write \\8 instead of \8. Or put an # in front of the string. Other characters also need to be escaped with the \ character:
"\\tssr>\"&\\8=f23'"
or this:
#"\tssr>""&\8=f23'"
the backslash \ is used for escaping special characters, like tab or newline. Because of that, the first character also needs to be escaped, because \t is the escape code for Tab.
Try escape sequence
Check this
\\tssr>\"&\\8=f23\'
See below.
var str = "\\tssr>\"&\\8=f23'";
I add a backslash to escape the special characters
The backslash is an escape character in C#, which forms part of an escape sequence.
You have two options: either use TWO backslashes (also known as escaping the backslash) for example var foo = "hello\\world";, or embed the sequence into a string literal eg var foo = #"hello\world";.
Try this:
string s = " \\tssr>\"&\\8=f23' ";

String.Format escaping VB vs C#

While searching on how to escape a single quote in String.Format, I found the answer at SO: Escaping single quote in String.Format()
It seems to be different for VB though. I tested it, and indeed C# needs
string s = DateTime.Now.ToString("MMM d \\'yy 'at' H:mmm");
while VB needs
Dim s As String = Now.ToString("MMM d \'yy 'at' H:mmm")
Why does C# need a double backslash, and VB a single backslash? This might be a bit of a silly question to C# users, but while I can read C#, I'm not used to writing it.
In C#, string literals can contain escape sequences such as \n for a new line or \t for a tab or \" for a quote. If you do not need the escaping, you can prefix the literal with # (eg: #"MMM ...") and get the same string a VB.
In VB, escaping is never allowed, so there is no need to escape the backslash.
The reason why is that C# supports escape sequences within string literals via the \ character. VB has no such escaping mechanisms and hence the single \ is interpretted as a \.
In C# you can get the same behavior by using verbatim strings
#"MMM d \'yy 'at' H:mmm"
In C# the backslash has a meaning (\n is newline \t tab ....).
So backlslahs itselft is an escape character - which you have to escape :)
Or place a AT-sign in front of the string - this makes a "non escaped string" (typically used for paths)
In c# \ will escape . Your text will become "MMM d \'yy 'at' H:mmm". You don't need to escape the ' character in a string. If you were to use " in the string on the other hand, you would need to escape it to not end your string "MMM d \"yy \"at\" H:mmm". Or you could also use the #"" string method which will automatically escape characters for you (not " though). So you could write #"this will not \n be two lines"

Categories