Will C Will C - 1 month ago 15
C# Question

Console WriteLine(var, var); not displaying second variable?

I'm writing a little text-based adventure in the console as one of my first projects in C#.

At a certain point, I want to do the following:

Console.WriteLine(intro);
var name = Console.ReadLine();
Console.Clear();
Console.WriteLine(replyOne, name, replyTwo);


However, on that last line, only the first variable (replyOne) is displayed. How can I display all the values?

Jcl Jcl
Answer

Depends on what's on replyOne, but you are using a Console.WriteLine overload that takes a format string as the first argument and a number of objects for substitution of that format string (this one). That's what's called Composite Formatting in .NET

If what you want to do is concatenate the strings, you can do it in several ways:

  1. Pass only one string to Console.WriteLine:

    Console.WriteLine(replyOne + name + replyTwo);
    
  2. Use a format string... this would use the same overload you are using now, but passing a formatting string for substitution on the first argument:

    Console.WriteLine("{0}{1}{2}", replyOne, name, replyTwo);
    
  3. Use an interpolated string (C# 6 and up only)

    Console.WriteLine($"{replyOne}{name}{replyTwo}");
    
Comments