- 3.1. Introduction
- 3.2. A Simple C# App: Displaying a Line of Text
- 3.3. Creating a Simple App in Visual Studio
- 3.4. Modifying Your Simple C# App
- 3.5. Formatting Text with Console.Write and Console.WriteLine
- 3.6. Another C# App: 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.13 outputs the strings "Welcome to" and "C# Programming!" with WriteLine.
Fig. 3.13 Displaying multiple lines of text with string formatting.
1
// Fig. 3.13: Welcome4.cs
2
// Displaying multiple lines of text with string formatting.
3
using System;4
5
public class Welcome46
{7
// Main method begins execution of C# app
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
Line 10
Console.WriteLine( "{0}\n{1}",
"Welcome to",
"C# Programming!" );
calls method Console.WriteLine to display the app’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.
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.
Format Strings and Format Items
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 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.