- 3.1 Introduction
- 3.2 A Simple C# Application: Displaying a Line of Text
- 3.3 Creating a Simple Application in Visual C# Express
- 3.4 Modifying Your Simple C# Application
- 3.5 Formatting Text with Console.Write and Console.WriteLine
- 3.6 Another C# Application: Adding Integers
- 3.7 Arithmetic
- 3.8 Decision Making: Equality and Relational Operators
- 3.9 Wrap-Up
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 |
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.