Search code examples
c#charspecial-characters

Why is char '\"' same as char '"'?


quick question. Why are both lines below valid?

char x = '\"';
char y = '"';

If " is a special character, shouldn't the second line be marked as incorrect?


Solution

  • If " is a special character, shouldn't the second line be marked as incorrect?

    No, because the rules of the language don't require " to be escaped within a character literal, only within a string literal.

    It's consistent to allow it to be escaped either way, however. That way there's one set of escape sequences which applies to both character and string literals, although \U........ will fail for any code point which isn't represented by a single UTF-16 code unit.

    The difference is within section 2.4.4.5 of the C# spec (string literals) where the single-regular-string-literal-character production is:

    Any character except " (U+0022), \ (U+005C), and new-line-character

    compared with section 2.4.4.4 (character literals) where the single-character production is:

    Any character except ' (U+0027), \ (U+005C) and new-line-character

    As you can see, the opposite of your situation holds for ':

    string x = "'";
    string y = "\'";
    Console.WriteLine(x == y); // Strings are equivalent