C# escape sqeuence

Started by
4 comments, last by Toolmaker 18 years, 9 months ago
In C# the escape sequence \' is supposed to be used to create a single quote. However, after experimenting with string literals, I found that I could just put a ' in my string literal. For example: System.Console.WriteLine("'Hello, World'"); This code requires no escape sequence, so why in the world would anyone use the \' escape sequence?

www.computertutorials.org
computertutorials.org-all your computer needs...
Advertisement
How do you print the character "'" as a character type? '\''' :)
to print " you basicly use \".

www.computertutorials.org
computertutorials.org-all your computer needs...
The typical rule is that if you're making a string literal, you don't need to escape the single quotes, and if you're making a char literal, you don't need to escape the double quotes.

char a = '\'''; // makes a single quote charchar b = '"'; // makes a double quote charstring c = "'"; // makes a single quote stringstring d = "\""; // makes a double quote string


Whoa. The forums are screwing up the "char a" section.
can @ be used with chars the same way it can be used with strings?

string A = @" "" " //A contains "
char B = @' '' ' //B contains '

www.computertutorials.org
computertutorials.org-all your computer needs...
No, you can't do that. How is the compiler suppose to know which ' the closing one? Indeed, it can't.

As for using the @, it's only purpose of to prevent escaping. So instead of doing "c:\\my location\\somefile.dat" you can do @"c:\my location\somefile.dat".

And Nypyren just told you when to use the escape character.

For instance:
"And then, the bartender \"laughed\" at his joke"
Results in:
And then, the bartender "laughed" at his joke.

Toolmaker

This topic is closed to new replies.

Advertisement