Search code examples
c#c++ioconsole.writeline

Complex I/O using Console.WriteLine()


I'm currently teaching myself C# after years of working only in C++. Needless to say there has been a lot I've needed to relearn. My question here is as follows:

What's the best approach in a Windows Console application to print (write to the console window) complex information, involving multiple variables, strings of text, and newline characters?

Put more plainly, how would I translate something resembling the following C++ code into C#:

int x = 1; int y = 2; double a = 5.4;

cout << "I have " << x << " item(s), and need you to give" << endl
     << "me " << y << " item(s). This will cost you " << a << endl
     << "units." << endl;

In C++ this would print the following to the console:

I have 1 item(s), and need you to give

give me 2 item(s). This will cost you 5.4

units.

This example is totally arbitrary but I often have short yet complex messages like this one in my programs. Will I totally have to relearn how I format output, or is there analogous functionality in C# that I just haven't found yet (I've dug through a lot of Console.IO documentation).


Solution

  • You can specify place-holders in the string you write out to the console, and then provide values to replace those place-holders, like this:

    Console.WriteLine("I have {0} item(s), and need you to give\r\n" +
                      "me {1} item(s). This will cost you {2} \r\nunits.", x, y, a);
    

    I think for readability, I'd separate it:

    Console.WriteLine("I have {0} item(s), and need you to give", x);
    Console.WriteLine("me {0} item(s). This will cost you {1} ", y, a);
    Console.WriteLine("units.");
    

    As BradleyDotNet noted, the Console.WriteLine() method doesn't directly perform the magic. It calls String.Format, which in turn uses StringBuilder.AppendFormat.

    If you want to see what's going on internally, you can check out the source code here.