14.6. Implement a Type That Can Be Formatted

Problem

You need to implement a type that can create different string representations of its content based on the use of format specifiers for use in formatted strings.

Solution

Implement the System.IFormattable interface.

How It Works

The following code fragment demonstrates the use of format specifiers in the WriteLine method of the System.Console class. The codes in the braces (emphasized in the example) are the format specifiers.

Dim a As Double = 345678.5678
Dim b As UInteger = 12000
Dim c As Byte = 254

Console.WriteLine("a = {0}, b = {1}, and c = {2}", a, b, c)
Console.WriteLine("a = {0:c0}, b = {1:n4}, and c = {2,10:×5}", a, b, c)

When run on a machine configured with English (United States) ...

Get Visual Basic 2008 Recipes: A Problem-Solution Approach now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.