Home > Articles > Programming > C#

  • Print
  • + Share This
This chapter is from the book

3.5 Formatting Text with Console.Write and Console.WriteLine

Console methods Write and WriteLine also have the capability to display formatted data. Figure 3.17 outputs the strings "Welcome to" and "C# Programming!" with WriteLine.

Fig. 3.17. Displaying multiple lines of text with string formatting.

 1   // Fig. 3.17: Welcome4.cs
 2   // Displaying multiple lines of text with string formatting.
 3   using System;
 5   public class Welcome4
 6   {
 7      // Main method begins execution of C# application
 8      public static void Main( string[] args )
 9      {
10         Console.WriteLine( "{0}\n{1}", "Welcome to", "C# Programming!" );
11      } // end Main
12   } // end class Welcome4
Welcome to
C# Programming!

Line 10 calls method Console.WriteLine to display the application's output. The method call specifies three arguments. When a method requires multiple arguments, the arguments appear in a comma-separated list.

Most statements end with a semicolon (;). Therefore, line 10 represents only one statement. Large statements can be split over many lines, but there are some restrictions.

Method WriteLine's first argument is a format string that may consist of fixed text and format items. Fixed text is output by WriteLine, as in Fig. 3.1. Each format item is a placeholder for a value. Format items also may include optional formatting information.

Format items are enclosed in curly braces and contain a sequence of characters that tell the method which argument to use and how to format it. For example, the format item {0} is a placeholder for the first additional argument (because C# starts counting from 0), {1} is a placeholder for the second, and so on. The format string in line 10 specifies that WriteLine should output two arguments and that the first one should be followed by a newline character. So this example substitutes "Welcome to" for the {0} and "C# Programming!" for the {1}. The output shows that two lines of text are displayed. Because braces in a formatted string normally indicate a placeholder for text substitution, you must type two left braces ({{) or two right braces (}}) to insert a single left or right brace into a formatted string, respectively. We introduce additional formatting features as they're needed in our examples.

  • + Share This
  • 🔖 Save To Your Account