3

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).

John Saunders
  • 160,644
  • 26
  • 247
  • 397
user3776749
  • 667
  • 1
  • 10
  • 20
  • 1
    There is really no direct equivalent of `out <<` operator in C#. `String.Format`/`Console.Write`/`Console.WriteLine` are more like `printf` replacement, but it is what used in .Net all the time to format output (you indeed can customize formatting if you want) as covered in MSDN, duplicate question, or answer by Grant Winney. – Alexei Levenkov Jan 08 '15 at 02:07
  • Unlike forum sites, we don't use "Thanks", or "Any help appreciated", or signatures on [so]. See "[Should 'Hi', 'thanks,' taglines, and salutations be removed from posts?](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-removed-from-posts). Besides, it's "Thanks in advance", not "Thanks in advanced". – John Saunders Jan 09 '15 at 17:22

1 Answers1

8

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.

Grant Winney
  • 65,241
  • 13
  • 115
  • 165