Search code examples
c#stringconsole.writeline

Why do commas not work to include strings in WriteLine?


I am wondering why a '+' is needed in a scenario like this:

string name = "Rick";
Console.WriteLine("Hello, " + name);

I was under the impression that the '+' was needed to include a variable of another type, and a string could be included without one. Is this incorrect?

Further, if that is the case, then why does it simply skip the variable and not return an error in a situation like this:

string name = "Rick";
Console.WriteLine("Hello, " , name);

Thanks.


Solution

  • As far as the compiler is concerned, the second version is trying to pass a second parameter, which the WriteLine method is not overloaded for. The options you really have for this are as follows

    Console.WriteLine("Hello, " + name);
    Console.WriteLine($"Hello, {name}");
    Console.WriteLine(String.Format("Hello, {0}", name));