Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

c# - Why Console.WriteLine outputs text without a format string and the type name when using a format string?

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[]"
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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[]"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...