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

What does ' ' do in Console.Write();

I’m trying to write all the elements of an array and this works ofcourse:

foreach (int i in arr)
{
    Console.Write(i + " ");
}

but this:

foreach (int i in arr)
{
    Console.Write(i + ' ');
}

returns something completely different. Why is that?

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

Edit:
Let’s say i have this array: [1, 3, 2, 8, 5, 4]. If I use the method with " " it prints just fine. If i use ' ' though it prints this: 333534403736.

>Solution :

Single quote represents a single character with the value ' ' (which is transformed to 32) where as a double quote appends a null terminator '\0' to the end of the string, so " " is actually " \0" and is larger in one byte than the intended size.

So for example, the iterations can be translated to:

1 + 32 // 33
3 + 32 // 35
2 + 32 // 34
8 + 32 // 40
5 + 32 // 37
4 + 32 // 36

Hence, the print will be: 333534403736

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