0

I using the codes below to print out the reverse name of a user input but I couldn't understand why the Console.WriteLine call prints out "Your reverse name is: System.Char[]"? If I just type Console.WriteLine(reverseName), it print out the reverse name correctly. What is different in this code? Couldn't understand why the usage a placeholder would give different output? Isn't it refer to the same information in reverseName?

static void Main(string[] args)
{
    var name = "Alice";
    char[] reverseName = new char[name.Length];
    for (var i = name.Length - 1; i > -1; i--)
    {
        reverseName[i] = name[name.Length - 1 - i];
    }
    
    Console.WriteLine(reverseName); // "ecilA"
    Console.WriteLine("Your reverse name is: {0} ", reverseName); 
       // "Your reverse name is: System.Char[]"
}
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
chuackt
  • 145
  • 5
  • Its because you cant print non-standard types. Char[] will have to be printed as a string so you need to convert that first to a string, `string.Concatenate(Reversenames)` would join the characters and create the string for you. – Jawad Jan 06 '21 at 04:43
  • `Console.WriteLine(char[])` and `Console.WriteLine(string, params object[] args)` are two different methods. – Fabio Jan 06 '21 at 04:43
  • Do you see `Your reverse name is: is:system.char[]`? That's because the default `ToString` method prints out the name of the type. You need to convert your char array to a string. One way is to change the second argument to `WriteLine` to `new String(Reversenames)` – Flydog57 Jan 06 '21 at 04:44
  • 1
    Consider rewording your posts _title_ to be more informative. This will help current and future readers via search engines –  Jan 06 '21 at 04:44
  • Thanks for solving my confusion, was learning from online video but never aware it is 2 different method so output 2 different result. – chuackt Jan 06 '21 at 04:49
  • Also, please change this part of your question `at the console writeline it print out your name is:system.char[]?` to something like `the Console.WriteLine call prints out "Your reverse name is: System.Char[]"` As it's written it's very hard to follow (in a large part because what it says is wrong) – Flydog57 Jan 06 '21 at 04:51
  • About reverse string you can try https://stackoverflow.com/questions/228038/best-way-to-reverse-a-string – MichaelMao Jan 06 '21 at 07:11

1 Answers1

4

In both cases you are actually calling different methods. See Member Overloading

When you call Console.WriteLine(Reversenames) you execute method WriteLine(Char[]), which will convert char array into string.

When you call Console.WriteLine("some text", Reversenames) you execute method WriteLine(String, Object[]), which will call .ToString() on every object given after the placeholder. new char[] {}.ToString() returns exactly what you see "system.char[]"

Fabio
  • 31,528
  • 4
  • 33
  • 72