Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WriteLine char[ ] + something

Tags:

c#

char

why this strange thing happens that when I try to write char[] word to a console via

Console.WriteLine(word);

I got a correct result, but when I write

Console.WriteLine(word + " something");

I get " System.Char[] something "?

like image 592
AuBa Avatar asked Nov 18 '25 18:11

AuBa


1 Answers

This happens because your first attempt is writing out a char array, which Console.WriteLine accepts as valid input using an overload.

Console.WriteLine(word);

But your second result appears wrong because you are combining a char[] with a string literal. So Console.WriteLine tries to make your char[] also a string, by doing this:

Console.WriteLine(word.ToString() + " something");

Notice it calls .ToString() on the word (internally) to make it a string. The ToString method on the char[] returns it's type not it's value. Thus giving you the odd result.

You can fix it by doing:

Console.WriteLine(new string(word) + " something");
like image 109
Scott Avatar answered Nov 21 '25 08:11

Scott



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!