Formatting Console Output

During these first few chapters, you have certainly noticed numerous occurrences of the tokens {0}, {1}, and the like embedded within a string literal. The .NET platform introduces a new style of string formatting, which can be used by any .NET programming language. Simply put, when you are defining a string literal that contains segments of data whose value is not known until runtime, you are able to specify a placeholder within the literal using this curly-bracket syntax. At runtime, the value(s) passed into Console.WriteLine() are substituted for each placeholder. To illustrate, update your current Main() method as follows:

Sub Main()

' Specify string placeholders and values to use at ' runtime.

Dim theInt As Integer = 90 Dim theDouble As Double = 9.99 Dim theBool As Boolean = True Console.WriteLine("Value of theInt: {0}", theInt) Console.WriteLine("theDouble is {0} and theBool is {1}.", _ theDouble, theBool) End Sub

The first parameter to WriteLine() represents a string literal that contains optional placeholders designated by {0}, {1}, {2}, and so forth. Be very aware that the first ordinal number of a curly-bracket placeholder always begins with 0. The remaining parameters to WriteLine() are simply the values to be inserted into the respective placeholders (in this case, an Integer, a Double, and a Boolean).

Note If you have a fewer number of uniquely numbered curly-bracket placeholders than fill arguments, you will receive a FormatException exception at runtime.

It is also permissible for a given placeholder to repeat within a given string. For example, if you are a Beatles fan and want to build the string "9, Number 9, Number 9", you would write:

Console.WriteLine("{0}, Number {0}, Number {0}", 9)

Also know that it is possible to position each placeholder in any location within a string literal, and you need not follow an increasing sequence. For example, consider the following code snippet:

Console.WriteLine("{1}, {0}, {2}", 10, 20, 30)

Was this article helpful?

0 0

Post a comment