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 '\n' are the same since '\n' == 10 < 256, so the stored value should be the same no matter the encodiung, the top bits all being 0s in both cases…
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 = ((byte)'\n').ToString();
var s2 = '\n'.ToString();
If you use you debugger you’ll see the s1 is "10", and s2 is "\n" (i.e. a string with one newline character).