Search code examples
c#stringcharbyte

In c#, why does a string composed of (byte)'\n' not contain '\n'?


I just discovered that the code below returns false:

((byte)'\n').ToString().Contains('\n') // -> false

While this one returns true:

'\n'.ToString().Contains('\n') // -> true

Why is that? The char codes of (byte)'\n' and (char)'\n' are the same since '\n' == 10. This number can be expressed as both a byte (1B) and a char (2B) because 10 < 256, so the stored value should be the same no matter the encoding...

I don't have a clue why this happens, being relatively new to typed languages.


Solution

  • '\n'.ToString() converts the char \n to string, and the result is a one character string with a newline.
    (see the documentation for Char.ToString).
    ► When you check if it contains a newline, the result is naturally true.

    ((byte)'\n').ToString() first converts the char \n to a byte, meaning a 8 bit intergral value of value 10. Then 10 is converted to string and the result is "10".
    (see the documentation for Byte.ToString).
    ► This string does not contain a newline and therefore you get false from Contains.

    You can observe it using the following snippet:

    var s1 = '\n'.ToString();
    var s2 = ((byte)'\n').ToString();
    

    If you use you debugger you'll see that s1 is "\n" (i.e. a string with one newline character) but s2 is "10".