Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 '\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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading