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.

Figure 3.17. Printing multiple lines of text with string formatting.

1 // Fig. 3.17: Welcome4.cs 2 // Printing multiple lines of text with string formatting. 3 using System; 4 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} {1}", "Welcome to", "C# Programming!" ); 11 } // end method Main 12 } // end class Welcome4  

Welcome to C# Programming!

Line 10

Console.WriteLine( "{0} {1}", "Welcome to", "C# Programming!" );

calls method Console.WriteLine to display the application's output. The method call specifies three arguments. When a method requires multiple arguments, the arguments are separated with commas (,)this is known as a comma-separated list.

Good Programming Practice 3 7

Place a space after each comma (,) in an argument list to make applications more readable.

Remember that all 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.

Common Programming Error 3 6

Splitting a statement in the middle of an identifier or a string is a syntax error.

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 we demonstrated 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, etc. 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. Note that because braces in a formatted string normally indicate a placeholder for text substitution, you must type two left braces () to insert a single left or right brace into a formatted string, respectively. We introduce additional formatting features as they are needed in our examples.

Another C# Application Adding Integers

Категории