The code in Chapter 1 glazed over the utility of the Console.WriteLine method. Actually this method has some powerful output string formatting capabilities, which are summarized in this section. Listing 2.1 shows a WriteLine method with a format string and parameters. Listing 2.1 Console.WriteLine Method with Formatted String (HelloTime.cs)using System; class HelloTime { static void Main() { string name = "Joe"; Console.WriteLine("Hello, {0}! Today is {1}.", name, DateTime.Now); Console.ReadLine(); } } The first parameter to WriteLine is a format string with placeholders, identified by numbers surrounded by curly braces. The placeholder numbers begin at 0 and continue, as shown in Listing 2.1, where the first placeholder is {0} and the second is {1}. Parameters following the format parameter replace the placeholders, in order of occurrence, when the formatting occurs at runtime. There are several more ways to perform string formatting: using the concatenation operator (+) and using the String.Format method. Listing 2.2 shows how to use each of these. Listing 2.2 More String Formatting (CountDown.cs)using System; class CountDown { static void Main() { string countDown = String.Format("{0}, {1}, ...", 10, 9); Console.WriteLine("countDown = " + countDown); Console.ReadLine(); } } The static Format method of the String type formats strings just like the WriteLine, except that it returns the formatted string rather than printing it to the console. Another means of formatting, which is convenient but less powerful, is the concatenation operator (+).
|