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

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

I'm sorry if this is a duplicate question - I can't believe I'm the only idiot to not work this one out, but I also couldn't find anything that answered my question. I suspect I'm being really stupid but can't for the life of me work this one out.

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 stupid am I being?

EDIT: Thanks all. Lots of useful answers here. Looks like I have much to learn.

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