WSC
WSC

Reputation: 992

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?

Upvotes: 0

Views: 850

Answers (5)

Jcl
Jcl

Reputation: 28272

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}");
    

Upvotes: 2

ChrisF
ChrisF

Reputation: 137178

If you want Console.WriteLine to output a formatted string the first argument has to be the string that contains the placeholders that define the formatting. So assuming you just want to output the three strings consecutively, you'll need something like this:

Console.WriteLine("{0} {1} {2}", replyOne, name, replyTwo);

which will output the three strings separated by spaces.

You can replace the spaces by commas, newlines (\n) or tabs (\t) to get the formatting you need.

Upvotes: 1

Universus
Universus

Reputation: 406

Console.WriteLine("{0},{1},{2}",replyOne,name,replyTwo);

Upvotes: 0

Peter Duniho
Peter Duniho

Reputation: 70701

Try this instead:

Console.WriteLine(replyOne + name + replyTwo);

Or something similar.

As you're calling the method right now, it's treating the replyOne value as the format for the output, not an individual output item. And of course, your format doesn't have a {0} or {1} for the format arguments in the call, name and replyTwo, so they are omitted.

You can just concatenate the output text yourself, as above, as use that as the entire format (without any format arguments at all).

There are, of course, lots of other options for formatting the output. The above fits what you've posted so far.

Upvotes: 0

zerkms
zerkms

Reputation: 255035

In the multi-argument overloads of the Console.WriteLine the first parameter is supposed to be a format string, and everything else as a substitution values.

See Console.WriteLine Method (String, Object) for details.

Upvotes: 1

Related Questions