Sign in to follow this  
sevak

C# escape sqeuence

Recommended Posts

sevak    100
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?

Share this post


Link to post
Share on other sites
Nypyren    12074
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 char
char b = '"'; // makes a double quote char
string c = "'"; // makes a single quote string
string d = "\""; // makes a double quote string


Whoa. The forums are screwing up the "char a" section.

Share this post


Link to post
Share on other sites
sevak    100
can @ be used with chars the same way it can be used with strings?

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

Share this post


Link to post
Share on other sites
Toolmaker    967
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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this